Eurig Jones
Eurig Jones

Reputation: 8543

RxJava Scheduler to observe on main thread

If I write something like this, then both the operation and notification will be on the current thread...

Observable.fromCallable(() -> "Do Something")
    .subscribe(System.out::println);

If I do the operation on a background thread like this, then both the operation and notification will be on a background thread...

Observable.fromCallable(() -> "Do Something")
    .subscribeOn(Schedulers.io())
    .subscribe(System.out::println);

If I want to observe on the main thread and do in the background in Android I would do...

Observable.fromCallable(() -> "Do Something")
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe(System.out::println);

But If I was writing a standard Java program, what is the equivalent to state that you want to observe on the main thread?

Upvotes: 22

Views: 13836

Answers (2)

Dmitry
Dmitry

Reputation: 902

For RxJava2 use "blockingSubscribe()"

Flowable.fromArray(1, 2, 3)
                .subscribeOn(Schedulers.computation())
                .blockingSubscribe(integer -> {
                    System.out.println(Thread.currentThread().getName());
                });

Upvotes: 16

Tassos Bassoukos
Tassos Bassoukos

Reputation: 16142

Convert the Observable to a BlockingObservable via .toBlocking(); this gives you blocking methods to wait for completion, get one item, etc.

Upvotes: 7

Related Questions