paul
paul

Reputation: 13471

SubscribeOn main thread

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.

Upvotes: 0

Views: 204

Answers (2)

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

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.

Upvotes: 0

N&#225;ndor Előd Fekete
N&#225;ndor Előd Fekete

Reputation: 7098

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

Upvotes: 1

Related Questions