예제 #1
0
 @Override
 public void createCategory(String newCategoryLabel) {
   mRxCategory
       .getAllCategories()
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(
           categories -> {
             int totalNumber = categories.size();
             if (!TextUtils.isEmpty(newCategoryLabel)) {
               mRxCategory
                   .saveCategory(newCategoryLabel, 0, totalNumber, true)
                   .observeOn(AndroidSchedulers.mainThread())
                   .subscribe(
                       categories1 -> {
                         boolean success = false;
                         for (Category category : categories1) {
                           if (category.getLabel().equals(newCategoryLabel)) {
                             mAlbumView.changeActivityListMenuCategoryChecked(category);
                             EventBus.getDefault().post(new CategoryCreateEvent());
                             success = true;
                             break;
                           }
                         }
                         if (!success) {
                           mAlbumView.showToast(
                               mContext.getResources().getString(R.string.toast_fail));
                         }
                       });
             } else {
               mAlbumView.showToast(mContext.getResources().getString(R.string.toast_fail));
             }
           });
 }
예제 #2
0
 @Override
 public void onResume() {
   super.onResume();
   friendInfoSub =
       toxSingleton
           .friendListAndRequestsSubject
           .observeOn(AndroidSchedulers.mainThread())
           .subscribe(
               new Action1<Tuple<ArrayList<FriendInfo>, ArrayList<FriendRequest>>>() {
                 @Override
                 public void call(
                     Tuple<ArrayList<FriendInfo>, ArrayList<FriendRequest>> friendstuple) {
                   updateContacts(friendstuple);
                 }
               });
   keySub =
       toxSingleton
           .activeKeySubject
           .observeOn(AndroidSchedulers.mainThread())
           .subscribe(
               new Action1<String>() {
                 @Override
                 public void call(String s) {
                   Log.d("ContactsFragment", "key subject");
                   activeKey = s;
                   setSelectionToKey(activeKey);
                 }
               });
 }
 @OnClick(R.id.test_btn)
 public void onClick() {
   Toast.makeText(CustomViewActivity.this, "click!", Toast.LENGTH_SHORT).show();
   Observable.interval(1000, TimeUnit.MILLISECONDS)
       .subscribeOn(AndroidSchedulers.mainThread())
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(
           new Action1<Long>() {
             @Override
             public void call(Long aLong) {
               mTestBtn.setAngleRange(mTestBtn.getAngleRange() + 20);
               Log.i("plus", "=======================");
             }
           });
 }
예제 #4
0
 @Override
 public void sortData() {
   mRxPhotoNote
       .findByCategoryId(mCategoryId, mAlbumSortKind)
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(photoNoteList -> mAlbumView.notifyDataSetChanged());
 }
예제 #5
0
 @Override
 public void deletePhotos() {
   // 注意java.util.ConcurrentModificationException at
   // java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
   mRxPhotoNote
       .findByCategoryId(mCategoryId, mAlbumSortKind)
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(
           photoNoteList -> {
             TreeMap<Integer, PhotoNote> map = getTreeMap();
             for (int i = 0; i < photoNoteList.size(); i++) {
               PhotoNote photoNote = photoNoteList.get(i);
               if (photoNote.isSelected()) {
                 map.put(i, photoNote);
               }
             }
             int times = 0;
             for (Map.Entry<Integer, PhotoNote> entry : map.entrySet()) {
               photoNoteList.remove(entry.getValue());
               mAlbumView.notifyItemRemoved(entry.getKey() - times);
               times++;
               mRxPhotoNote.deletePhotoNote(entry.getValue()).subscribe();
             }
             EventBus.getDefault().post(new PhotoNoteDeleteEvent());
           });
 }
예제 #6
0
  public void onLogout() {
    Settings.getInstance().setUserOnline(false);
    if (SMTHApplication.activeUser != null) {
      SMTHApplication.activeUser.setId("guest");
    }
    UpdateNavigationViewHeader();

    SMTHHelper helper = SMTHHelper.getInstance();
    helper
        .wService
        .logout()
        .observeOn(AndroidSchedulers.mainThread())
        .subscribeOn(Schedulers.io())
        .subscribe(
            new Subscriber<AjaxResponse>() {
              @Override
              public void onCompleted() {}

              @Override
              public void onError(Throwable e) {
                Toast.makeText(MainActivity.this, "退出登录失败!\n" + e.toString(), Toast.LENGTH_LONG)
                    .show();
              }

              @Override
              public void onNext(AjaxResponse ajaxResponse) {
                Toast.makeText(MainActivity.this, ajaxResponse.getAjax_msg(), Toast.LENGTH_LONG)
                    .show();
              }
            });
  }
  /**
   * Bind text view to HTML string
   *
   * @param view
   * @param html
   * @param id
   * @return this image getter
   */
  public HttpImageGetter bind(final TextView view, final String html, final Object id) {
    if (TextUtils.isEmpty(html)) return hide(view);

    CharSequence encoded = fullHtmlCache.get(id);
    if (encoded != null) return show(view, encoded);

    encoded = rawHtmlCache.get(id);
    if (encoded == null) {
      if (!html.matches("<[a-z][\\s\\S]*>")) {
        RequestMarkdownDTO markdownDTO = new RequestMarkdownDTO();
        markdownDTO.text = html;
        new GetMarkdownClient(markdownDTO)
            .observable()
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                new ObserverAdapter<String>() {
                  @Override
                  public void onNext(String data) {
                    continueBind(view, data, id);
                  }

                  @Override
                  public void onError(Throwable e) {
                    continueBind(view, html, id);
                  }
                });
      } else {
        return continueBind(view, html, id);
      }
    }
    return this;
  }
  private void loadList(List<AppInfo> apps) {
    mRecyclerView.setVisibility(View.VISIBLE);

    Observable<AppInfo> observableApp = Observable.from(apps);

    Observable<Long> tictoc = Observable.interval(1, TimeUnit.SECONDS);

    Observable.zip(observableApp, tictoc, this::updateTitle)
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Observer<AppInfo>() {
              @Override
              public void onCompleted() {
                Toast.makeText(getActivity(), "Here is the list!", Toast.LENGTH_LONG).show();
              }

              @Override
              public void onError(Throwable e) {
                mSwipeRefreshLayout.setRefreshing(false);
                Toast.makeText(getActivity(), "Something went wrong!", Toast.LENGTH_SHORT).show();
              }

              @Override
              public void onNext(AppInfo appInfo) {
                if (mSwipeRefreshLayout.isRefreshing()) {
                  mSwipeRefreshLayout.setRefreshing(false);
                }
                mAddedApps.add(appInfo);
                int position = mAddedApps.size() - 1;
                mAdapter.addApplication(position, appInfo);
                mRecyclerView.smoothScrollToPosition(position);
              }
            });
  }
예제 #9
0
  public void search(
      String searchString,
      int rSize,
      int startPageLocation,
      String userIp,
      String size,
      final Callback callback) {
    Log.d("itemListApp", "NetworkManager search");

    imageService
        .search(version, searchString, rSize, startPageLocation, userIp, size)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Subscriber<NetworkResponseData>() {
              @Override
              public void onCompleted() {}

              @Override
              public void onError(Throwable e) {
                Log.d("itemListApp", "network onError: " + e.getMessage());
                callback.failure(null);
              }

              @Override
              public void onNext(NetworkResponseData networkResponseData) {
                Log.d("itemListApp", "network success: " + networkResponseData.getClass());
                if (networkResponseData.getResponseData() != null) {
                  callback.success(networkResponseData.getResponseData().getResults(), null);
                }
              }
            });
  }
  public void loadMoreClientList(int offset, int limit) {
    checkViewAttached();
    getMvpView().showProgressbar(true);
    if (mSubscription != null) mSubscription.unsubscribe();
    mSubscription =
        mDataManager
            .getAllClients(offset, limit)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(
                new Subscriber<Page<Client>>() {
                  @Override
                  public void onCompleted() {
                    getMvpView().showProgressbar(false);
                  }

                  @Override
                  public void onError(Throwable e) {
                    getMvpView().showProgressbar(false);
                    getMvpView()
                        .showFetchingError(
                            "\"Cannot get clients, There might be some" + " problem!\"");
                  }

                  @Override
                  public void onNext(Page<Client> clientPage) {
                    getMvpView().showProgressbar(false);
                    getMvpView().showMoreClientList(clientPage);
                  }
                });
  }
  private void findSensorId(final Transmitter transmitter, final SensorType sensorType) {
    RelayrSdk.getRelayrApi()
        .getTransmitterDevices(transmitter.id)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Subscriber<List<TransmitterDevice>>() {
              @Override
              public void onCompleted() {}

              @Override
              public void onError(Throwable e) {
                showToast(R.string.error_loading_devices);
              }

              @Override
              public void onNext(List<TransmitterDevice> devices) {
                boolean deviceFound = false;

                for (TransmitterDevice device : devices) {
                  if (device.getModel().equals(sensorType.getModel())) {
                    Storage.getRule().sensorId = device.id;
                    saveTransmitterData(transmitter);
                    deviceFound = true;
                  }
                }

                if (!deviceFound) showToast(R.string.error_finding_device);

                switchToEdit(FragmentName.SENSOR);
              }
            });
  }
예제 #12
0
  private void initializeSubscriptions() {
    if (downloadsSubscription != null && !downloadsSubscription.isUnsubscribed())
      downloadsSubscription.unsubscribe();

    if (threadsNumberSubscription != null && !threadsNumberSubscription.isUnsubscribed())
      threadsNumberSubscription.unsubscribe();

    threadsNumberSubscription =
        preferences.downloadThreads().asObservable().subscribe(threadsNumber::onNext);

    downloadsSubscription =
        downloadsQueueSubject
            .lift(new DynamicConcurrentMergeOperator<>(this::downloadChapter, threadsNumber))
            .onBackpressureBuffer()
            .observeOn(AndroidSchedulers.mainThread())
            .map(download -> areAllDownloadsFinished())
            .subscribe(
                finished -> {
                  if (finished) {
                    DownloadService.stop(context);
                  }
                },
                e -> Timber.e(e.getCause(), e.getMessage()));

    if (!isRunning) {
      isRunning = true;
      runningSubject.onNext(true);
    }
  }
예제 #13
0
  private void load(final User selectedAssignee) {
    showIndeterminate(R.string.loading_collaborators);
    new GetAssigneesClient(InfoUtils.createRepoInfo(repository))
        .observable()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .compose(activity.<List<User>>bindToLifecycle())
        .subscribe(
            new ObserverAdapter<List<User>>() {
              @Override
              public void onError(Throwable error) {
                dismissProgress();
                Log.d(TAG, "Exception loading collaborators", error);
                ToastUtils.show(activity, error, R.string.error_collaborators_load);
              }

              @Override
              public void onNext(List<User> users) {
                Map<String, User> loadedCollaborators = new TreeMap<>(CASE_INSENSITIVE_ORDER);
                for (User user : users) loadedCollaborators.put(user.login, user);
                collaborators = loadedCollaborators;

                dismissProgress();
                show(selectedAssignee);
              }
            });
  }
예제 #14
0
  /** ****** Get A route Between source & destination ****** */
  private void getRoute(LatLng srcLatLng, LatLng distLatLng) {
    final RouteDrawer routeDrawer =
        new RouteDrawer.RouteDrawerBuilder(gMap)
            .withColor(Color.BLUE)
            .withWidth(5)
            .withAlpha(0.0f)
            .withMarkerIcon(
                BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_YELLOW))
            .build();

    RouteRest routeRest = new RouteRest();
    routeRest
        .getJsonDirections(srcLatLng, distLatLng, TravelMode.DRIVING)
        .observeOn(AndroidSchedulers.mainThread())
        .map(
            new Func1<String, Routes>() {
              @Override
              public Routes call(String s) {
                return new RouteJsonParser<Routes>().parse(s, Routes.class);
              }
            })
        .subscribe(
            new Action1<Routes>() {
              @Override
              public void call(Routes r) {
                routeDrawer.drawPath(r);
              }
            });
  }
 // 加载Apk
 private void loadApks() {
   // 异步加载, 防止Apk过多, 影响速度
   Observable.just(getApkFromInstall())
       .subscribeOn(Schedulers.newThread())
       .observeOn(AndroidSchedulers.mainThread())
       .subscribe(mApkListAdapter::setApkItems);
 }
예제 #16
0
  /**
   * Makes an API call to get the top or recent Kus. Checks that it isn't an empty dataset and
   * updates the view Uses the KuCardAdapter class for button functionality and loading data
   */
  public void UpdateKus(String sort) {
    ApiClient.getKukyApiClient(AuthHelper.getCreds(getContext()))
        .getKus(sort, String.valueOf(getUserId()))
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Subscriber<KuListResponse>() {
              @Override
              public final void onCompleted() {
                // do nothing
              }

              @Override
              public final void onError(Throwable e) {
                Log.e("KukyAPI Error", e.getMessage());
              }

              @Override
              public final void onNext(KuListResponse response) {
                mkuList = response.getKus();
                checkForKus(mkuList);
                mKuCardAdapter.setList(mkuList);
                mKuCardAdapter.notifyDataSetChanged();
                Log.d(TAG, "Received data");
              }
            });
  }
  private HttpImageGetter continueBind(final TextView view, final String html, final Object id) {
    CharSequence encoded = HtmlUtils.encode(html, loading);
    if (containsImages(html)) rawHtmlCache.put(id, encoded);
    else {
      rawHtmlCache.remove(id);
      fullHtmlCache.put(id, encoded);
      return show(view, encoded);
    }

    if (TextUtils.isEmpty(encoded)) return hide(view);

    show(view, encoded);
    view.setTag(id);
    Observable.just(html)
        .subscribeOn(Schedulers.computation())
        .map(
            new Func1<String, CharSequence>() {
              @Override
              public CharSequence call(String htmlString) {
                return HtmlUtils.encode(htmlString, HttpImageGetter.this);
              }
            })
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new ObserverAdapter<CharSequence>() {
              @Override
              public void onNext(CharSequence htmlCharSequence) {
                fullHtmlCache.put(id, htmlCharSequence);
                if (id.equals(view.getTag())) {
                  show(view, htmlCharSequence);
                }
              }
            });
    return this;
  }
예제 #18
0
  private void initData() {
    String token = getIntent().getStringExtra(INTENT_TOKEN);
    String uid = getIntent().getStringExtra(INTENT_UID);
    UserBean userBean = (UserBean) getIntent().getSerializableExtra(INTENT_USER);
    if (userBean == null) {
      ApiServiceHelper.getApiService(Constants.WEIBO_BASE_URL, AccountApiService.class)
          .getUserInfoByUID(token, uid)
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              new Observer<UserBean>() {
                @Override
                public void onCompleted() {}

                @Override
                public void onError(Throwable e) {
                  Log.i("UserDetailActivity", "onError - error : " + e.getMessage());
                }

                @Override
                public void onNext(UserBean userBean) {
                  view.updateView(userBean);
                }
              });
    } else {
      view.updateView(userBean);
    }
  }
  private void startPresentation(String tag) {

    RestClient.service()
        .presentationJoin(presentation.getId(), user.getId(), tag)
        .subscribeOn(Schedulers.newThread())
        .observeOn(AndroidSchedulers.mainThread())
        .compose(this.<BaseResponse>bindToLifecycle())
        .subscribe(
            new Action1<BaseResponse>() {

              @Override
              public void call(BaseResponse joinResponse) {
                UnityActivity.startActivity(NfcDetectActivity.this, user, presentation);
              }
            },
            new Action1<Throwable>() {
              @Override
              public void call(Throwable throwable) {
                throwable.printStackTrace();
                Toast.makeText(
                        NfcDetectActivity.this, "Unable to join, try again!", Toast.LENGTH_LONG)
                    .show();
              }
            });
  }
예제 #20
0
 private void doLogin(final String username, String password) {
   subscription.add(
       api.getUserInfo(username)
           .observeOn(Schedulers.io())
           .subscribeOn(Schedulers.io())
           .observeOn(AndroidSchedulers.mainThread())
           .subscribe(
               new Action1<Result<User>>() {
                 @Override
                 public void call(Result<User> t) {
                   showProgress(false);
                   if (t.getStatus() == 200) {
                     Toast.makeText(getApplicationContext(), t.getMsg(), Toast.LENGTH_SHORT)
                         .show();
                     String sid = t.getData().getUname();
                   }
                 }
               },
               new Action1<Throwable>() {
                 @Override
                 public void call(Throwable throwable) {
                   GlobalUtils.showToastShort(LoginActivity.this, getString(R.string.net_error));
                   showProgress(false);
                 }
               }));
 }
예제 #21
0
  @Override
  public synchronized Observable<AccessToken> registerForAccessTokenUpdates(String code) {
    Timber.d("registerForAccessTokenUpdates");
    if (loadAccessTokenSubscription == null || loadAccessTokenSubscription.isUnsubscribed()) {
      Timber.d("no loading in progress, starting new one");
      loadAccessTokenSubscription =
          loadAccessTokenObservable(code)
              .subscribeOn(Schedulers.io())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(
                  new DefaultSubscriber<AccessToken>() {

                    @Override
                    public void onError(Throwable throwable) {
                      Timber.e("accessTokenSubject.onError");
                      accessTokenSubject.onError(throwable);
                    }

                    @Override
                    public void onNext(AccessToken data) {
                      Timber.d("accessTokenSubject.onNext: " + data);
                      // Caching accessToken data
                      accessToken = data;
                      accessTokenSubject.onNext(accessToken);
                    }
                  });
    }
    return accessTokenSubject.asObservable();
  }
  private void deleteRepository() {
    MaterialDialog.Builder builder = new MaterialDialog.Builder(getActivity());
    builder.progress(true, 0);
    builder.content(R.string.deleting_repository);
    deleteRepoDialog = builder.show();
    DeleteRepoClient deleteRepoClient = new DeleteRepoClient(getActivity(), repoInfo);
    deleteRepoClient
        .observable()
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe(
            new Subscriber<Response>() {
              @Override
              public void onCompleted() {}

              @Override
              public void onError(Throwable e) {
                Toast.makeText(getActivity(), "Repository delete failed", Toast.LENGTH_SHORT)
                    .show();
              }

              @Override
              public void onNext(Response response) {
                if (getActivity() != null) {
                  if (deleteRepoDialog != null) {
                    deleteRepoDialog.dismiss();
                  }
                  getActivity().setResult(Activity.RESULT_CANCELED);
                  getActivity().finish();
                }
              }
            });
  }
예제 #23
0
  public Subscription subscribeData(Observer<List<GankBeauty>> observer) {
    if (mCache == null) {
      mCache = BehaviorSubject.create();
      Observable.create(
              new Observable.OnSubscribe<List<GankBeauty>>() {

                @Override
                public void call(Subscriber<? super List<GankBeauty>> subscriber) {
                  List<GankBeauty> itemList = getDataFromDisk(DATA_FILE_NAME);
                  if (ListUtils.isEmpty(itemList)) {
                    Logger.d("Load data from network");
                    setDataSource(DATA_SOURCE_NETWORK);
                    loadFromNetwork();
                  } else {
                    Logger.d("Load data from disk");
                    setDataSource(DATA_SOURCE_DISK);
                    subscriber.onNext(itemList);
                  }
                }
              })
          .subscribeOn(Schedulers.io())
          .subscribe(mCache);
    } else {
      Logger.d("Load data from memory.");
      setDataSource(DATA_SOURCE_MEMORY);
    }
    return mCache.observeOn(AndroidSchedulers.mainThread()).subscribe(observer);
  }
  public static void handleException(final Context context, final Throwable e) {
    if (Looper.myLooper() != Looper.getMainLooper()) {
      AndroidSchedulers.mainThread()
          .createWorker()
          .schedule(
              new Action0() {
                @Override
                public void call() {
                  handleException(context, e);
                }
              });
      return;
    }
    if (context == null || e == null) {
      return;
    }
    if (e instanceof OutOfMemoryError) {
      ToastUtils.show(
          ParallelwordApplacation.get().getResources().getString(R.string.outof_memory),
          Toast.LENGTH_SHORT);
      e.printStackTrace();
    }
    if (e instanceof AuthException) {
      // 处理验证异常
      e.printStackTrace();
    }

    e.printStackTrace();
    // 添加其他异常处理
  }
예제 #25
0
  @Override
  public void onBugReportSubmit(final BugReportView.Report report) {
    if (report.includeLogs) {
      lumberYard
          .save()
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              new Subscriber<File>() {
                @Override
                public void onCompleted() {
                  // NO-OP.
                }

                @Override
                public void onError(Throwable e) {
                  Toast.makeText(context, "Couldn't attach the logs.", Toast.LENGTH_SHORT).show();
                  submitReport(report, null);
                }

                @Override
                public void onNext(File logs) {
                  submitReport(report, logs);
                }
              });
    } else {
      submitReport(report, null);
    }
  }
 @Override
 public void onClick(View v) {
   if (v.getId() == R.id.btn_obdervable_test1) {
     if (RxBus.hasObservers()) {
       RxBus.send(new TapEvent());
     }
   } else if (v.getId() == R.id.btn_obdervable_test2) {
     if (RxBus.hasObservers()) {
       mRemoteServerEngine
           .loadMoreDataRx(1)
           .subscribeOn(Schedulers.io())
           .observeOn(Schedulers.io())
           .flatMap(refreshModels -> Observable.from(refreshModels))
           .filter(refreshModel -> !refreshModel.title.contains("4"))
           .take(3)
           .observeOn(AndroidSchedulers.mainThread())
           .subscribe(
               refreshModel -> {
                 if (RxBus.hasObservers()) {
                   RxBus.send(new RefreshModelEvent(refreshModel));
                 }
               });
     }
   }
 }
예제 #27
0
  public Observable<Object> ping() {

    return pingService
        .ping()
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread());
  }
예제 #28
0
        public void onServiceConnected(ComponentName className, IBinder service) {
          // mService = new Messenger(service);

          rviService = ((RviService.RviBinder) service).getService();

          rviService
              .servicesAvailable()
              .subscribeOn(Schedulers.newThread())
              .observeOn(AndroidSchedulers.mainThread())
              .subscribe(
                  new Observer<String>() {
                    @Override
                    public void onCompleted() {}

                    @Override
                    public void onError(Throwable e) {}

                    @Override
                    public void onNext(String s) {
                      Log.i(TAG, "X: " + s);
                      fragment.onNewServiceDiscovered(s);
                      // Toast.makeText(LockActivity.this, "X: "+s, Toast.LENGTH_SHORT).show();
                    }
                  });

          // Tell the user about this for our demo.
          Toast.makeText(LockActivity.this, "RVI service connected", Toast.LENGTH_SHORT).show();
        }
예제 #29
0
  /**
   * Delete contact call
   *
   * @param contact
   */
  private void deleteContact(Contact contact) {

    apiService
        .deleteContact(contact.getId())
        .observeOn(AndroidSchedulers.mainThread())
        .doOnRequest(aLong -> showLoader("Deleting contact..."))
        .doOnNext(
            contact1 -> {
              hideLoader();

              Message.show(getContext(), "Contact Deleted");
              activity.supportFinishAfterTransition();
            })
        .doOnError(throwable -> hideLoader())
        .subscribe(
            new RetroSubscriber<Contact>() {
              @Override
              public void onRetrofitError(RetrofitError error) {
                super.onRetrofitError(error);

                String message;

                if (error.getKind() == RetrofitError.Kind.NETWORK) message = "Network error";
                else message = "Something went wrong";

                Message.show(getContext(), message);
              }
            });
  }
예제 #30
0
  private void populateItems(SkylarkClient client) {

    RecyclerView recycleView = (RecyclerView) findViewById(R.id.setsdetail_recycler_view);

    recycleView.setLayoutManager(new LinearLayoutManager(this));

    final EpisodeAdapter adapter = new EpisodeAdapter(getApplicationContext());
    recycleView.setAdapter(adapter);

    ArrayList<ParcelableItem> parcelableArrayListExtra =
        getIntent().getParcelableArrayListExtra(EXTRA_ITEMS);

    for (Item item : parcelableArrayListExtra) {
      client
          .fetchEpisode(item)
          .subscribeOn(Schedulers.io())
          .observeOn(AndroidSchedulers.mainThread())
          .subscribe(
              new Action1<Episode>() {
                @Override
                public void call(Episode episode) {
                  adapter.add(episode);
                  adapter.notifyItemInserted(adapter.getItemCount());
                }
              });
    }
  }