SubscribeOn main thread

225 Views Asked by At

How can I set the async operator of Observable to run in the main thread instead in another thread. Or at least set to get the result in the main thread once we finish.

    @Test
    public void retryWhen() {
        Scheduler scheduler = Schedulers.newThread();
        Single.just("single")
                .map(word -> null)
                .map(Object::toString)
                .retryWhen(ot ->
                        ot.doOnNext(t -> System.out.println("Retry mechanism:" + t))
                                .filter(t -> t instanceof NullPointerException && cont < 5)
                                .flatMap(t -> Observable.timer(100, TimeUnit.MILLISECONDS,scheduler))
                                .doOnNext(t -> cont++)
                                .switchIfEmpty(Observable.error(new NullPointerException())))
                .subscribeOn(scheduler)
                .subscribe(System.out::println, System.out::println);
//        new TestSubscriber()
//                .awaitTerminalEvent(1000, TimeUnit.MILLISECONDS);
    }

I´m trying observerOn and subscribeOn but both are used to set in which thread you want the execution. But in my case I want the execution or the end of it in the same thread where I run the test

Right now the only way to see the prints are just blocking and waiting for the execution.

Regards.

2

There are 2 best solutions below

6
On

You could use Observable.toBlocking() to get a BlockingObservable and use that to extract your results in your tests.

1
On

If you don't specify observeOn/subscribeOn and no operator or Observable changes the thread, then when you subscribe to the observable it will do all the processing during the subscription.