@Test public void testMergeAsyncThenObserveOn() { int NUM = (int) (RxRingBuffer.SIZE * 4.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable<Integer> merged = Observable.merge( incrementingIntegers(c1).subscribeOn(Schedulers.computation()), incrementingIntegers(c2).subscribeOn(Schedulers.computation())); merged.observeOn(Schedulers.newThread()).take(NUM).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println( "testMergeAsyncThenObserveOn => Received: " + ts.getOnNextEvents().size() + " Emitted: " + c1.get() + " / " + c2.get()); assertEquals(NUM, ts.getOnNextEvents().size()); // either one can starve the other, but neither should be capable of doing more than 5 batches // (taking 4.1) // TODO is it possible to make this deterministic rather than one possibly starving the other? // benjchristensen => In general I'd say it's not worth trying to make it so, as "fair" // algoritms generally take a performance hit // akarnokd => run this in a loop over 10k times and never saw values get as high as 7*SIZE, but // since observeOn delays the unsubscription non-deterministically, the test will remain // unreliable assertTrue(c1.get() < RxRingBuffer.SIZE * 7); assertTrue(c2.get() < RxRingBuffer.SIZE * 7); }
@Test public void testZipAsync() { int NUM = (int) (RxRingBuffer.SIZE * 2.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable<Integer> zipped = Observable.zip( incrementingIntegers(c1).subscribeOn(Schedulers.computation()), incrementingIntegers(c2).subscribeOn(Schedulers.computation()), new Func2<Integer, Integer, Integer>() { @Override public Integer call(Integer t1, Integer t2) { return t1 + t2; } }); zipped.take(NUM).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println( "testZipAsync => Received: " + ts.getOnNextEvents().size() + " Emitted: " + c1.get() + " / " + c2.get()); assertEquals(NUM, ts.getOnNextEvents().size()); assertTrue(c1.get() < RxRingBuffer.SIZE * 3); assertTrue(c2.get() < RxRingBuffer.SIZE * 3); }
@Test public void testMergeAsync() { int NUM = (int) (RxRingBuffer.SIZE * 4.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable<Integer> merged = Observable.merge( incrementingIntegers(c1).subscribeOn(Schedulers.computation()), incrementingIntegers(c2).subscribeOn(Schedulers.computation())); merged.take(NUM).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println( "testMergeAsync => Received: " + ts.getOnNextEvents().size() + " Emitted: " + c1.get() + " / " + c2.get()); assertEquals(NUM, ts.getOnNextEvents().size()); // either one can starve the other, but neither should be capable of doing more than 5 batches // (taking 4.1) // TODO is it possible to make this deterministic rather than one possibly starving the other? // benjchristensen => In general I'd say it's not worth trying to make it so, as "fair" // algoritms generally take a performance hit assertTrue(c1.get() < RxRingBuffer.SIZE * 5); assertTrue(c2.get() < RxRingBuffer.SIZE * 5); }
@Test public void testMergeAsyncThenObserveOnLoop() { for (int i = 0; i < 500; i++) { if (i % 10 == 0) { System.out.println("testMergeAsyncThenObserveOnLoop >> " + i); } // Verify there is no MissingBackpressureException int NUM = (int) (RxRingBuffer.SIZE * 4.1); AtomicInteger c1 = new AtomicInteger(); AtomicInteger c2 = new AtomicInteger(); TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable<Integer> merged = Observable.merge( incrementingIntegers(c1).subscribeOn(Schedulers.computation()), incrementingIntegers(c2).subscribeOn(Schedulers.computation())); merged.observeOn(Schedulers.io()).take(NUM).subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); System.out.println( "testMergeAsyncThenObserveOn => Received: " + ts.getOnNextEvents().size() + " Emitted: " + c1.get() + " / " + c2.get()); assertEquals(NUM, ts.getOnNextEvents().size()); } }
public RetentionFragment() { final Gson gson = new GsonBuilder() .registerTypeAdapter(Message.class, new Message.Deserializer()) .registerTypeAdapter(MessageType.class, new MessageType.SerializerDeserializer()) .create(); final OkHttpClient okHttpClient = new OkHttpClient(); final RxWebSockets webSockets = new RxWebSockets( okHttpClient, new Request.Builder() .get() .url("ws://10.10.0.2:8080/ws") .addHeader("Sec-WebSocket-Protocol", "chat") .build()); final GsonObjectSerializer serializer = new GsonObjectSerializer(gson, Message.class); final RxObjectWebSockets jsonWebSockets = new RxObjectWebSockets(webSockets, serializer); final SocketConnection socketConnection = new SocketConnectionImpl(jsonWebSockets, Schedulers.io()); presenter = new MainPresenter( new Socket(socketConnection, Schedulers.io()), Schedulers.io(), AndroidSchedulers.mainThread()); }
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); } })); }
@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)); } }); } } }
public void addFriend(final FriendRequest friendRequest) { FriendshipAddForm dataForm = new FriendshipAddForm(); dataForm.friend_id = friendRequest.getUid(); friendshipResource .save(dataForm) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .subscribe( response -> { // TODO show add friend Tip Friend friend = new Friend(); friend.setUid(friendRequest.getUid()); friend.setUsername(friendRequest.getUsername()); friend.setNickname( TextUtils.isEmpty(friendRequest.getNickname()) ? friendRequest.getDisplayName() : friendRequest.getNickname()); friend.setAvatar(friendRequest.getAvatar()); friendDao.insert(friend); }, error -> { // TODO show error info }); // update friendRequest friendRequest.setStatus(FriendRequestStatus.ACCEPT.name()); friendRequestDao.update(friendRequest); }
@Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: finish(); break; case R.id.save: subscription = Observable.create( new Observable.OnSubscribe<File>() { @Override public void call(Subscriber<? super File> subscriber) { try { File f = Glide.with(PhotoActivity.this) .load(url) .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL) .get() // needs to be called on background thread ; subscriber.onNext(f); } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } } }) .subscribeOn(Schedulers.newThread()) .observeOn(Schedulers.io()) .map( new Func1<File, String>() { @Override public String call(File file) { Log.i("path", file.getPath()); FileUtil.copyFile( file.getPath(), Environment.getExternalStorageDirectory() + "/friends/" + url.substring(url.lastIndexOf("/") + 1)); return file.getPath(); } }) .observeOn(AndroidSchedulers.mainThread()) .subscribe( new Action1<String>() { @Override public void call(String s) { toast( "已保存至" + Environment.getExternalStorageDirectory() + "/friends/" + url.substring(url.lastIndexOf("/") + 1)); } }); break; } return super.onOptionsItemSelected(item); }
@Test public void testAsyncChild() { TestSubscriber<Integer> ts = new TestSubscriber<Integer>(); Observable.range(0, 100000) .observeOn(Schedulers.newThread()) .observeOn(Schedulers.newThread()) .subscribe(ts); ts.awaitTerminalEvent(); ts.assertNoErrors(); }
@Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); when(mRepository.getAll()).thenReturn(Observable.just(DataUtils.provideMockTodoList())); mViewModel = new TodoListViewModelImpl( RuntimeEnvironment.application, mRepository, new RxUtils.SchedulerHolder(Schedulers.immediate(), Schedulers.immediate())); }
public static void newsList(int id, int page, Subscriber<BaseBean.NewsListBean> subscriber) { RxUtils.unsubscribe(); RxUtils.subscription = Network.getTngouApi() .getNewsList(id, page) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()) .subscribe(subscriber); }
private void addPostLoadSubscription(final PostAdapter adapter) { if (adapter.shouldShowLoadingIndicator()) adapter.showLoadingIndicator(); Map<String, String> options = adapter.getAdapterOptions(); String tag = options.get(PaginationAdapter.KEY_TAG); final String anchor = options.get(PaginationAdapter.KEY_ANCHOR); String nextPage = options.get(PaginationAdapter.KEY_NEXT_PAGE); Observable<PostResponse> observable; if (tag.equals(mPopularText)) { observable = mDataManager.getPopularPosts(nextPage, anchor); } else if (tag.equals(mEditorsPicksText)) { observable = mDataManager.getEditorsPicksPosts(nextPage, anchor); } else { observable = mDataManager.getPostsByTag(tag, nextPage, anchor); } mCompositeSubscription.add( observable .observeOn(AndroidSchedulers.mainThread()) .subscribeOn(Schedulers.io()) .unsubscribeOn(Schedulers.io()) .subscribe( new Subscriber<PostResponse>() { @Override public void onCompleted() {} @Override public void onError(Throwable e) { adapter.removeLoadingIndicator(); if (adapter.size() == 0) { adapter.showTryAgainCard(); } else { Toast.makeText( getActivity(), getString(R.string.error_message_loading_more_posts), Toast.LENGTH_SHORT) .show(); } Timber.e("There was an error loading the posts", e); } @Override public void onNext(PostResponse postResponse) { adapter.removeLoadingIndicator(); if (adapter.size() == 0 && postResponse.data.records.isEmpty()) { adapter.showReloadCard(); } else { if (anchor == null) adapter.setAnchor(postResponse.data.anchorStr); adapter.setNextPage(postResponse.data.nextPage); adapter.addAllItems(postResponse.data.records); } } })); }
@Setup public void setup() { source = Single.just(1); flatmapped = source.flatMap( new Func1<Integer, Single<Integer>>() { @Override public Single<Integer> call(Integer t) { return Single.just(t); } }); flatmapped = source.flatMap( new Func1<Integer, Single<Integer>>() { @Override public Single<Integer> call(Integer t) { return source; } }); sourceObserveOn = source.observeOn(Schedulers.computation()); sourceSubscribeOn = source.subscribeOn(Schedulers.computation()); // ---------- scheduledExecutor = Executors.newScheduledThreadPool(1); Scheduler s = Schedulers.from(scheduledExecutor); sourceObserveOnScheduledExecutor = source.observeOn(s); sourceSubscribeOnScheduledExecutor = source.subscribeOn(s); // ---------- executor = Executors.newSingleThreadExecutor(); Scheduler se = Schedulers.from(executor); sourceObserveOnExecutor = source.observeOn(se); sourceSubscribeOnExecutor = source.subscribeOn(se); // -------- // Scheduler fj = Schedulers.from(ForkJoinPool.commonPool()); // sourceObserveOnFJ = source.observeOn(fj); // sourceSubscribeOnFJ = source.subscribeOn(fj); }
private void onFavoriteItemSelected(boolean favorited) { Observable<Boolean> obsAction; if (favorited) { obsAction = Observable.create( (Subscriber<? super Boolean> subscriber) -> { try { FavoritesUtils.addToFavorites(getActivity(), FAVORITE_VIDEOS, mFeedItem); mFeedItem = new FeedItem.Builder(mFeedItem).setFavorited(true).build(); subscriber.onNext(true); } catch (Exception e) { Timber.w(e, "Unable to add FeedItem to favorites"); subscriber.onError(e); } subscriber.onCompleted(); }); obsAction = AndroidObservable.bindFragment(this, obsAction).subscribeOn(Schedulers.io()); bindSubscription( obsAction.subscribe( result -> { if (result) { Toast.makeText(getActivity(), R.string.added_to_favorites, Toast.LENGTH_SHORT) .show(); } configureOverflow(result); })); } else { obsAction = Observable.create( (Subscriber<? super Boolean> subscriber) -> { try { FavoritesUtils.removeFromFavorites(getActivity(), FAVORITE_VIDEOS, mFeedItem); mFeedItem = new FeedItem.Builder(mFeedItem).setFavorited(false).build(); subscriber.onNext(false); } catch (Exception e) { Timber.w(e, "Unable to remove FeedItem from favorites"); subscriber.onError(e); } subscriber.onCompleted(); }); obsAction = AndroidObservable.bindFragment(this, obsAction).subscribeOn(Schedulers.io()); bindSubscription( obsAction.subscribe( result -> { if (!result) { Toast.makeText(getActivity(), R.string.removed_from_favorites, Toast.LENGTH_SHORT) .show(); } configureOverflow(result); })); } }
public CloudPicDataStore( ICommonItemService picService, ICommentService commentService, PicItemDao picItemDao, MetaDao metaDao) { this.picService = picService; this.commentService = commentService; this.picItemDao = picItemDao; this.metaDao = metaDao; this.refreshComment = picItems -> { CloudPicDataStore.this .commentService .getDuoshuoCommentList( Joiner.on(",") .join( Lists.transform( picItems, picItem -> Constants.THREAD_PREFIX + picItem.getPicId()))) .subscribeOn(Schedulers.io()) .observeOn(Schedulers.io()) .subscribe( commentCountResponse -> { // TODO: optimize this with tx List<PicItem> picItemList = new ArrayList<PicItem>(); for (String key : commentCountResponse.getResponse().keySet()) { CommentCountResponse.CommentCount commentCount = commentCountResponse.getResponse().get(key); Long picId = commentCount.getCommonItemId(); logger.info("{}:{}", commentCount.getThreadKey(), commentCount.getCount()); PicItem picItem = CloudPicDataStore.this .picItemDao .queryBuilder() .where(PicItemDao.Properties.PicId.eq(picId)) .unique(); if (picItem != null) { picItem.setCommentCount(commentCount.getCount()); picItem.setThreadId(commentCount.getThreadId()); picItemList.add(picItem); } } if (picItemList.size() > 0) CloudPicDataStore.this.picItemDao.updateInTx(picItemList); }, throwable -> {}); }; }
@Override public Observable<List<TMWRule>> loadRemoteRules() { return ruleApi .getAllRules(new DbSearch(Storage.loadUserId())) .subscribeOn(Schedulers.io()) .map( new Func1<DbDocuments<DbRule>, List<TMWRule>>() { @Override public List<TMWRule> call(DbDocuments<DbRule> docs) { new Delete().from(TMWRule.class).execute(); ActiveAndroid.beginTransaction(); try { for (DbRule dbRule : docs.getDocuments()) { checkGcmNotification(dbRule); TMWRule rule = DataMapper.toRule(dbRule); rule.save(); } ActiveAndroid.setTransactionSuccessful(); } finally { ActiveAndroid.endTransaction(); } return new Select().from(TMWRule.class).execute(); } }); }
@Test public void test() { TestSubscriber<Object> tester = new TestSubscriber<>(); TestScheduler scheduler = Schedulers.test(); Observable<Long> left = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler).take(6); Observable<Long> right = Observable.interval(200, TimeUnit.MILLISECONDS, scheduler).take(3); left.groupJoin( right, i -> Observable.never(), i -> Observable.timer(0, TimeUnit.MILLISECONDS, scheduler), (l, rs) -> rs.toList().map(rl -> Tuple.create(l, rl))) .flatMap(i -> i) .subscribe(tester); scheduler.advanceTimeTo(600, TimeUnit.MILLISECONDS); tester.assertReceivedOnNext( Arrays.asList( Tuple.create(0L, Arrays.asList(0L, 1L, 2L)), Tuple.create(1L, Arrays.asList(0L, 1L, 2L)), Tuple.create(2L, Arrays.asList(1L, 2L)), Tuple.create(3L, Arrays.asList(1L, 2L)), Tuple.create(4L, Arrays.asList(2L)), Tuple.create(5L, Arrays.asList(2L)))); }
@Test public void exampleEquivalence() { TestScheduler scheduler = Schedulers.test(); TestSubscriber<Object> testerJoin = new TestSubscriber<>(); TestSubscriber<Object> testerGroupJoin = new TestSubscriber<>(); Observable<Long> left = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler); Observable<Long> right = Observable.interval(100, TimeUnit.MILLISECONDS, scheduler); left.join( right, i -> Observable.timer(150, TimeUnit.MILLISECONDS, scheduler), i -> Observable.timer(0, TimeUnit.MILLISECONDS, scheduler), (l, r) -> Tuple.create(l, r)) .take(10) .subscribe(testerJoin); left.groupJoin( right, i -> Observable.timer(150, TimeUnit.MILLISECONDS, scheduler), i -> Observable.timer(0, TimeUnit.MILLISECONDS, scheduler), (l, rs) -> rs.map(r -> Tuple.create(l, r))) .flatMap(i -> i) .take(10) .subscribe(testerGroupJoin); scheduler.advanceTimeTo(600, TimeUnit.MILLISECONDS); testerJoin.assertReceivedOnNext(testerGroupJoin.getOnNextEvents()); }
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); }
private void loadFromNetwork() { Network.getGankApi() .getBeautyList(100, 1) .subscribeOn(Schedulers.io()) .map(GankBeautyResultToGankBeauty.getInstance()) .doOnNext( new Action1<List<GankBeauty>>() { @Override public void call(List<GankBeauty> gankBeauties) { Logger.d("Cache data to disk."); String gsonStr = new Gson().toJson(gankBeauties); mDiskCache.put(DATA_FILE_NAME, gsonStr); } }) .subscribe( new Action1<List<GankBeauty>>() { @Override public void call(List<GankBeauty> gankBeauties) { Logger.d("Get data from network."); mCache.onNext(gankBeauties); } }, new Action1<Throwable>() { @Override public void call(Throwable throwable) { throwable.printStackTrace(); } }); }
public Observable<Object> ping() { return pingService .ping() .subscribeOn(Schedulers.io()) .observeOn(AndroidSchedulers.mainThread()); }
@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); } }
private void fetchGitHubSearch(@NonNull final String searchString) { Preconditions.checkNotNull(searchString, "Search String cannot be null."); Log.d(TAG, "fetchGitHubSearch(" + searchString + ")"); if (requestMap.containsKey(searchString.hashCode()) && !requestMap.get(searchString.hashCode()).isUnsubscribed()) { Log.d(TAG, "Found an ongoing request for repository " + searchString); return; } final String uri = gitHubRepositorySearchStore.getUriForKey(searchString).toString(); Subscription subscription = createNetworkObservable(searchString) .subscribeOn(Schedulers.computation()) .map( (repositories) -> { final List<Integer> repositoryIds = new ArrayList<>(); for (GitHubRepository repository : repositories) { gitHubRepositoryStore.put(repository); repositoryIds.add(repository.getId()); } return new GitHubRepositorySearch(searchString, repositoryIds); }) .doOnCompleted(() -> completeRequest(uri)) .doOnError(doOnError(uri)) .subscribe( gitHubRepositorySearchStore::put, e -> Log.e( TAG, "Error fetching GitHub repository search for '" + searchString + "'", e)); requestMap.put(searchString.hashCode(), subscription); startRequest(uri); }
@Before public void setUp() { today = new LocalDate(2015, Date.FEBRUARY, 8); when(clock.now()).thenReturn(today); Scheduler s = Schedulers.immediate(); sut = new SortedEventsLoader(repo, s, clock); }
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); } }); }
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); } } }); }
@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(); }
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(); } }); }
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); } }