rx.schedulers.Schedulers Java Examples

The following examples show how to use rx.schedulers.Schedulers. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: CommonRemoteDataSource.java    From DoingDaily with Apache License 2.0 6 votes vote down vote up
@Override
public void getShowPictures(Map<String, String> options, @NonNull final ShowPictureCallback callback) {
    NetworkManager.getShowAPI().getPictures(options).subscribeOn(Schedulers.newThread())//子线程访问网络
            .observeOn(AndroidSchedulers.mainThread())//回调到主线程
            .subscribe(new Action1<PictureShowBean>() {
                @Override
                public void call(PictureShowBean bean) {
                    callback.onPicturesLoaded(bean);
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    callback.onDataNotAvailable();
                }
            });
}
 
Example #2
Source File: QiscusChatPresenter.java    From qiscus-sdk-android with Apache License 2.0 6 votes vote down vote up
private void sendComment(QiscusComment qiscusComment) {
    view.onSendingComment(qiscusComment);
    Subscription subscription = QiscusApi.getInstance().sendMessage(qiscusComment)
            .doOnSubscribe(() -> Qiscus.getDataStore().addOrUpdate(qiscusComment))
            .doOnNext(this::commentSuccess)
            .doOnError(throwable -> commentFail(throwable, qiscusComment))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindToLifecycle())
            .subscribe(commentSend -> {
                if (commentSend.getRoomId() == room.getId()) {
                    view.onSuccessSendComment(commentSend);
                }
            }, throwable -> {
                QiscusErrorLogger.print(throwable);
                throwable.printStackTrace();
                if (qiscusComment.getRoomId() == room.getId()) {
                    view.onFailedSendComment(qiscusComment);
                }
            });

    pendingTask.put(qiscusComment, subscription);
}
 
Example #3
Source File: CommunityController.java    From nono-android with GNU General Public License v3.0 6 votes vote down vote up
public static void postNew(String answerDetail,String questionId){
    ServiceFactory.getPostService().newPost(
            AuthBody.getAuthBodyMap(
                    new Pair<>("access_token", MyApp.getInstance().userInfo.quickAskToken),
                    new Pair<>("user_name", MyApp.getInstance().userInfo.username),
                    new Pair<>("key_detail", answerDetail),
                    new Pair<>("question_id", questionId))
    )
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Action1<WonderFull>() {
                @Override
                public void call(WonderFull wonderFull) {
                    if(wonderFull.state_code ==0){
                        EventBus.getDefault().post(new PostAnswerSuccessEvent());
                    }else{
                        EventBus.getDefault().post(new PostAnswerFailEvent());
                    }
                }
            }, new Action1<Throwable>() {
                @Override
                public void call(Throwable throwable) {
                    EventBus.getDefault().post(new PostAnswerFailEvent());
                }
            });
}
 
Example #4
Source File: EventPresenter.java    From RoomBookerMVP with MIT License 6 votes vote down vote up
private void getEvent() {
    fetchEventUsecase.setEventParams(calendarId, eventId);
    eventView.showLoading();
    eventSubscribtion = fetchEventUsecase.execute()
            .subscribeOn(Schedulers.io())

            .onErrorReturn(new Func1<Throwable, Event>() {
                @Override
                public Event call(Throwable throwable) {
                    eventView.showError();
                    return null;
                }
            })
            .subscribe(new Action1<Event>() {
                @Override
                public void call(Event event) {
                    eventView.showEvent(event);
                }
            });
}
 
Example #5
Source File: MainPresenter.java    From Stock-Hawk with Apache License 2.0 6 votes vote down vote up
public void deleteStock(String symbol) {
    checkViewAttached();
    mSubscriptions.add(mDataManager.deleteStock(symbol)
            .observeOn(AndroidSchedulers.mainThread())
            .subscribeOn(Schedulers.io())
            .subscribe(new Subscriber<Stocks>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {
                    Timber.e(e, "There was an error deleting the stock");
                    getMvpView().showError();
                }

                @Override
                public void onNext(Stocks stock) {
                    showStocks(stock);
                }
            })
    );
}
 
Example #6
Source File: AddToBucketActivity.java    From droidddle with Apache License 2.0 6 votes vote down vote up
@Override
public void onClicked(Bucket data) {
    if (!Utils.hasInternet(this)) {
        Toast.makeText(this, R.string.check_network, Toast.LENGTH_SHORT).show();
        return;
    }
    Observable<Response> observable = ApiFactory.getService(this).addShotToBucket(data.id, mShotId);
    observable.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(new SucessCallback<Response>(this, R.string.shot_add_to_bucket_success) {
                @Override
                public void call(Response o) {
                    super.call(o);
                    finish();
                }
            }, new ErrorCallback(this));
}
 
Example #7
Source File: QiscusComment.java    From qiscus-sdk-android with Apache License 2.0 6 votes vote down vote up
public void loadLinkPreviewData() {
    if (getType() == Type.LINK) {
        if (previewData != null) {
            linkPreviewListener.onLinkPreviewReady(this, previewData);
        } else {
            QiscusUrlScraper.getInstance()
                    .generatePreviewData(urls.get(0))
                    .doOnNext(previewData -> previewData.setUrl(urls.get(0)))
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(previewData -> {
                        this.previewData = previewData;
                        if (linkPreviewListener != null) {
                            linkPreviewListener.onLinkPreviewReady(this, previewData);
                        }
                    }, Throwable::printStackTrace);
        }
    }
}
 
Example #8
Source File: PostActivity.java    From materialup with Apache License 2.0 6 votes vote down vote up
private void setupDribbble() {
    commentsList.setAdapter(getLoadingCommentsAdapter());
    if (shot != null && shot.getImageUrl() == null) {
        loaderImage();
    }

    if (mFull) {
        handleContent(shot);
        return;
    }
    if (!Utils.hasInternet(this)) {
        Toast.makeText(this, R.string.check_network, Toast.LENGTH_SHORT).show();
        return;
    }

    Api.getApiService().getPostSidebar(shot.id)
            .map(muResponse -> JsoupUtil.getPostContent1(shot, muResponse))
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(content -> handleContent(content), new ErrorCallback(this));
}
 
Example #9
Source File: ProfileActivity.java    From openwebnet-android with MIT License 6 votes vote down vote up
private <T> void requestAction(Func0<Observable<T>> observableAction, Action1<T> onSuccess) {
    hideActions();

    if (utilityService.hasInternetAccess()) {
        observableAction.call()
            // better UX
            .delay(1 , TimeUnit.SECONDS)
            // max http timeout
            .timeout(5, TimeUnit.SECONDS)
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(onSuccess, error -> {
                swipeRefreshLayoutProfile.setRefreshing(false);
                log.error("requestAction: request failed", error);
                showSnackbar(R.string.error_request);
            });
    } else {
        // show empty list
        updateProfiles(Lists.newArrayList());
        // hide
        speedDialProfile.hide();
        log.warn("requestAction: connection unavailable");
        showSnackbar(R.string.error_connection);
    }
}
 
Example #10
Source File: PresenterImpl.java    From journaldev with MIT License 6 votes vote down vote up
@Override
public void loadData() {

    mView.showProgress();

    apiInterface.getData("10").subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<List<CryptoData>>() {
                @Override
                public void onCompleted() {
                    mView.showComplete();
                    mView.hideProgress();
                }

                @Override
                public void onError(Throwable e) {
                    mView.showError("Error occurred");
                    mView.hideProgress();
                }

                @Override
                public void onNext(List<CryptoData> data) {
                    mView.showData(data);
                }
            });
}
 
Example #11
Source File: UploaderTest.java    From RxUploader with Apache License 2.0 6 votes vote down vote up
@Test
public void testUploadFileNotFoundException() throws Exception {
    final File file = new File("invalid");
    final String jobId = "job-id";
     final Job job = Job.builder()
            .setId(jobId)
            .setStatus(Status.createQueued(jobId))
            .setMetadata(Collections.emptyMap())
            .setFilepath("invalid")
            .setMimeType("text/plain")
            .build();

    final UploadService service = mock(UploadService.class);

    final Uploader uploader = new Uploader(service, Schedulers.io());
    final TestSubscriber<Status> ts = TestSubscriber.create();
    uploader.upload(job, file).subscribe(ts);

    ts.awaitTerminalEvent(1, TimeUnit.SECONDS);
    ts.assertError(FileNotFoundException.class);
    ts.assertNoValues();
}
 
Example #12
Source File: GetProductInfosCommand.java    From code with Apache License 2.0 6 votes vote down vote up
@Override
protected Observable<ProductInfo> construct() {
    return Observable.create(new Observable.OnSubscribe<ProductInfo>() {
        @Override
        public void call(Subscriber<? super ProductInfo> subscriber) {
            try {
                for (String productId : productIds) {
                    String url = "http://127.0.0.1:8082/getProductInfo?productId=" + productId;
                    String response = HttpClientUtils.sendGetRequest(url);
                    ProductInfo productInfo = JSONObject.parseObject(response, ProductInfo.class);
                    subscriber.onNext(productInfo);
                }
                subscriber.onCompleted();
            } catch (Exception e) {
                subscriber.onError(e);
            }
        }
    }).subscribeOn(Schedulers.io());
}
 
Example #13
Source File: MainActivity.java    From RxPaper with MIT License 6 votes vote down vote up
public void readCustom(View view) {
	RxPaper.book(mCustomBook)
		.read(PERSON_KEY, defaultValue)
		.subscribeOn(Schedulers.io())
		.observeOn(AndroidSchedulers.mainThread())
		.subscribe(new Subscriber<Person>() {
			@Override
			public void onCompleted() {

			}

			@Override
			public void onError(Throwable e) {
				log(e.getMessage());

			}

			@Override
			public void onNext(Person person) {
				log(String.valueOf(person));
			}
		});
}
 
Example #14
Source File: RxFirebaseDatabaseTests.java    From RxFirebase with Apache License 2.0 6 votes vote down vote up
@Test
public void testObserveSingleWrongType() {

    TestSubscriber<WrongType> testSubscriber = new TestSubscriber<>();
    RxFirebaseDatabase.observeSingleValueEvent(mockDatabase, WrongType.class)
            .subscribeOn(Schedulers.immediate())
            .subscribe(testSubscriber);

    ArgumentCaptor<ValueEventListener> argument = ArgumentCaptor.forClass(ValueEventListener.class);
    verify(mockDatabase).addListenerForSingleValueEvent(argument.capture());
    argument.getValue().onDataChange(mockFirebaseDataSnapshot);

    testSubscriber.assertError(RuntimeException.class);
    testSubscriber.assertNotCompleted();
    testSubscriber.unsubscribe();
}
 
Example #15
Source File: NavigationDrawerFragment.java    From droidddle with Apache License 2.0 6 votes vote down vote up
public void updateUser(String accessToken) {
    if (mUser != null) {
        return;
    }
    try {
        if (!Utils.hasInternet(getActivity())) {
            return;
        }
        Observable<User> user = ApiFactory.getService(getActivity(), accessToken)
                .getOAuthUser();
        user.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe((u) -> {
                    updateData(u);
                }, new ErrorCallback(getActivity()));
    } catch (Exception e) {
        //TODO have NEP...
        e.printStackTrace();
    }
}
 
Example #16
Source File: Http.java    From trading-backtest with MIT License 6 votes vote down vote up
public static Observable<HttpResponse> get(String url, Consumer<HttpGet> configureRequest) {
    HttpGet request = new HttpGet(url);
    configureRequest.accept(request);

    return Observable.create(new OnSubscribe<HttpResponse>() {
        @Override public void call(Subscriber<? super HttpResponse> s) {
            try {
                log.debug("GET {}", url);
                s.onNext(getDefaultHttpClient().execute(request));
                s.onCompleted();
            } catch (IOException e) {
                s.onError(e);
            }
        }
    }).subscribeOn(Schedulers.io());
}
 
Example #17
Source File: BookDetailPresenter.java    From BookReader with Apache License 2.0 6 votes vote down vote up
public void getBookDetail(String bookId) {
    Subscription rxSubscription = bookApi.getBookDetail(bookId).subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Observer<BookDetail>() {
                @Override
                public void onNext(BookDetail data) {
                    if (data != null && mView != null) {
                        mView.showBookDetail(data);
                    }
                }

                @Override
                public void onCompleted() {
                }

                @Override
                public void onError(Throwable e) {
                    Log.e(TAG, "onError: " + e);
                }
            });
    addSubscrebe(rxSubscription);
}
 
Example #18
Source File: HomeActivity.java    From fingerpoetry-android with Apache License 2.0 6 votes vote down vote up
@Subscribe
    public void onLoginSuccess(LoginEvent event) {
        Timber.i("receive onLoginSuccess");
        updateNavData();
//        CommonHelper.getTopics(this);
//        CommonHelper.getUserTopics(this);
//        CommonHelper.getSites(this);
//        CommonHelper.getUserSites(this);
        User user = AccountLogic.getInstance().getNowUser();
        if (!user.getIsBasicSet() && Constants.isFirstLaunch()) {
            Constants.setFirstLaunch(false);
            user.setBasicSet(true);
            LoginData data = AccountLogic.getInstance().getLoginData();
            data.setUser(user);
            AccountLogic.getInstance().setLoginData(data);
            AccountApi accountApi = BookRetrofit.getInstance().getAccountApi();
            Map<String, Object> info = new HashMap<>();
            info.put("isBasicSet", user.getIsBasicSet());
            accountApi.update(info, AccountLogic.getInstance().getToken())
                    .subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(initObserver(HomeActivity.this));
            start(ChooseTopicFragment.newInstance(ChooseTopicFragment.ACTION_SET));
        }
    }
 
Example #19
Source File: StopActivity.java    From RxJava_RxAndroid with Apache License 2.0 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_stop);

    textView = (TextView) findViewById(R.id.textview);
    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            startActivity( new Intent( StopActivity.this , OtherActivity.class));
        }
    });

    //循环发送数字
    Observable.interval(0, 1, TimeUnit.SECONDS)
            .subscribeOn( Schedulers.io())
            .compose(this.<Long>bindUntilEvent(ActivityEvent.STOP ))   //当Activity执行Onstop()方法是解除订阅关系
            .observeOn( AndroidSchedulers.mainThread())
            .subscribe(new Action1<Long>() {
                @Override
                public void call(Long aLong) {
                    System.out.println("lifecycle-stop-" + aLong);
                    textView.setText( "" + aLong );
                }
            });
}
 
Example #20
Source File: ChatBll.java    From PlayTogether with Apache License 2.0 6 votes vote down vote up
/**
 * 压缩上传
 *
 * @return
 */
public Observable<AVFile> compressImageAndUpload(String path, int maxWidth, int maxHeight)
{
	return compressImage(path, maxWidth, maxHeight)
					.observeOn(Schedulers.io())
					.subscribeOn(Schedulers.computation())
					.flatMap(new Func1<AVFile, Observable<AVFile>>()
					{
						@Override
						public Observable<AVFile> call(AVFile avFile)
						{
							return uploadFile(avFile);
						}
					});


}
 
Example #21
Source File: RxJavaSimple.java    From ZZShow with Apache License 2.0 5 votes vote down vote up
/**
 *  测试线程控制
 */
public void testScheduler(){
    Observable.just(1,2,3,4,5)
            .subscribeOn(Schedulers.io()) // 指定 subscribe() 发生在 IO 线程
            .observeOn(AndroidSchedulers.mainThread())  // 指定 Subscriber 的回调发生在主线程
            .subscribe(new Action1<Integer>() {
                @Override
                public void call(Integer integer) {
                    Log.d(TAG,"number:"+integer);
                    Log.d(TAG,"currentThread:"+Thread.currentThread().toString());
                }
            });
}
 
Example #22
Source File: ItemSyncAdapterTest.java    From materialistic with Apache License 2.0 5 votes vote down vote up
@Test
public void testSyncWebCacheEmptyUrl() {
    new FavoriteManager(new InMemoryCache(), Schedulers.immediate(),
            mock(MaterialisticDatabase.SavedStoriesDao.class))
            .add(service, new Favorite("1", null, "title", System.currentTimeMillis()));
    assertThat(ShadowWebView.getLastGlobalLoadedUrl()).isNullOrEmpty();
}
 
Example #23
Source File: NowPlayingFragment.java    From vk_music_android with GNU General Public License v3.0 5 votes vote down vote up
@Override
protected void onCurrentAlbumArtChanged(Bitmap currentAlbumArt) {
    new Thread(() -> {
        Drawable currentDrawable = binding.albumLarge.getDrawable();
        if (currentDrawable == null) {
            currentDrawable = ResourcesCompat.getDrawable(getResources(), R.drawable.ic_album_placeholder, null);
        }
        BitmapDrawable albumArtDrawable = new BitmapDrawable(getResources(), currentAlbumArt);

        TransitionDrawable transitionDrawableSmall = new TransitionDrawable(new Drawable[]{currentDrawable, albumArtDrawable});
        transitionDrawableSmall.setCrossFadeEnabled(true);

        TransitionDrawable transitionDrawableLarge = new TransitionDrawable(new Drawable[]{currentDrawable, albumArtDrawable});
        transitionDrawableLarge.setCrossFadeEnabled(true);

        getActivity().runOnUiThread(() -> {
            binding.albumSmall.setImageDrawable(transitionDrawableSmall);
            binding.albumLarge.setImageDrawable(transitionDrawableLarge);

            transitionDrawableSmall.startTransition(getResources().getInteger(android.R.integer.config_mediumAnimTime));
            transitionDrawableLarge.startTransition(getResources().getInteger(android.R.integer.config_mediumAnimTime));
        });
    }).start();

    GraphicsUtil.isBottomDark(currentAlbumArt)
            .subscribeOn(Schedulers.newThread())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(isDark -> {
                binding.playbackPositionLabel.setTextColor(isDark ? Color.WHITE : Color.BLACK);
                binding.playbackRemainingLabel.setTextColor(isDark ? Color.WHITE : Color.BLACK);
            });
}
 
Example #24
Source File: Api.java    From ratebeer with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Performs a login on the server, ensures that the rate counts are updated in our local session and emits true on success
 */
public Observable<Boolean> login(String username, String password) {
	// @formatter:off
	return Observable.zip(
				// Combine the latest user counts
				routes.getUserInfo(KEY, username)
						.subscribeOn(Schedulers.newThread())
						.flatMapIterable(infos -> infos)
						.first(),
				// And sign in the user (get login cookies)
				getLoginRoute(username, password)
						.subscribeOn(Schedulers.newThread()),
				(userInfo, loginSuccess) -> userInfo)
			// Then add the user id the user's rate counts
			.flatMap(user -> Observable.zip(
					Observable.just(user),
					routes.getUserRateCount(KEY, user.userId)
							.flatMapIterable(userRateCounts -> userRateCounts),
					RxTuples.toPair()))
			// Store in our own instance the new user data
			.doOnNext(user -> Session.get().startSession(user.getValue0().userId, username, password, user.getValue1()))
			// Store the time of this last successful login to time out the session forcefully after some time
			.doOnNext(ignore -> lastSignIn = System.currentTimeMillis())
			// Return login success
			.map(ignore -> true);
	// @formatter:on
}
 
Example #25
Source File: QiscusChatPresenter.java    From qiscus-sdk-android with Apache License 2.0 5 votes vote down vote up
private void forwardFile(QiscusComment qiscusComment) {
    qiscusComment.setProgress(100);
    Subscription subscription = QiscusApi.getInstance().sendMessage(qiscusComment)
            .doOnSubscribe(() -> Qiscus.getDataStore().addOrUpdate(qiscusComment))
            .doOnNext(commentSend -> {
                qiscusComment.setDownloading(false);
                commentSuccess(commentSend);
            })
            .doOnError(throwable -> {
                qiscusComment.setDownloading(false);
                commentFail(throwable, qiscusComment);
            })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .compose(bindToLifecycle())
            .subscribe(commentSend -> {
                if (commentSend.getRoomId() == room.getId()) {
                    view.onSuccessSendComment(commentSend);
                }
            }, throwable -> {
                QiscusErrorLogger.print(throwable);
                throwable.printStackTrace();
                if (qiscusComment.getRoomId() == room.getId()) {
                    view.onFailedSendComment(qiscusComment);
                }
            });

    pendingTask.put(qiscusComment, subscription);
}
 
Example #26
Source File: RxJavaCreateTest.java    From AndroidSchool with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateUnsubscribed() throws Exception {
    Subscription subscription = RxJavaCreate.observableWithCreate()
            .subscribeOn(Schedulers.newThread())
            .subscribe(System.out::println);
    subscription.unsubscribe();
}
 
Example #27
Source File: ForumApi.java    From TLint with Apache License 2.0 5 votes vote down vote up
/**
 * 收藏帖子
 *
 * @param tid 帖子id
 */
public Observable<CollectData> addCollect(String tid) {
    Map<String, String> params = mRequestHelper.getHttpRequestMap();
    params.put("tid", tid);
    String sign = mRequestHelper.getRequestSign(params);
    return mForumService.addCollect(sign, params).subscribeOn(Schedulers.io());
}
 
Example #28
Source File: RxDataBase.java    From FakeWeather with Apache License 2.0 5 votes vote down vote up
public static <T extends DataSupport> Observable<T> getFirst(final Class<T> clazz) {
    return Observable.unsafeCreate(new Observable.OnSubscribe<T>() {
        @Override
        public void call(Subscriber<? super T> subscriber) {
            subscriber.onNext(DataSupport.findFirst(clazz));
            subscriber.onCompleted();
        }
    }).subscribeOn(Schedulers.io());
}
 
Example #29
Source File: LinksPresenterImpl.java    From redgram-for-reddit with GNU General Public License v3.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private Subscription getSearchSubscription(String subreddit, Map<String, String> params, boolean isNew) {
    return redditClient.executeSearch(subreddit, params, ((!isNew) ? linksView.getItems() : null))
            .compose(((BaseFragment)containerView.getContentContext()).bindToLifecycle())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<RedditListing>() {
                @Override
                public void onCompleted() {
                    //hide progress and show list
                    if(isNew){
                        containerView.hideLoading();
                    }else{
                        linksView.hideLoading();
                    }
                }

                @Override
                public void onError(Throwable e) {
                    if(isNew){
                        containerView.hideLoading();
                    }else{
                        linksView.hideLoading();
                    }
                    containerView.showErrorMessage(e.toString());
                }

                @Override
                public void onNext(RedditListing wrapper) {
                    if(isNew){
                        linksView.getItems().clear();
                        linksView.updateList(wrapper.getItems());
                    }else{
                        linksView.getItems().addAll(wrapper.getItems());
                        linksView.updateList();
                    }
                    loadMoreId = wrapper.getAfter();
                }
            });
}
 
Example #30
Source File: RxJavaExamplesTest.java    From Hands-On-Reactive-Programming-in-Spring-5 with MIT License 5 votes vote down vote up
@Test
public void deferSynchronousRequest() throws Exception {
   String query = "query";
   Observable.fromCallable(() -> doSlowSyncRequest(query))
      .subscribeOn(Schedulers.io())
      .subscribe(this::processResult);

   Thread.sleep(1000);
}