22

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?

Maroun
  • 94,125
  • 30
  • 188
  • 241
Eurig Jones
  • 8,226
  • 7
  • 52
  • 74
  • 3
    You need a blocking scheduler for this as Java main thread is not a pool/looper. This is only available for RxJava 2.x in the extensions project: https://github.com/akarnokd/RxJava2Extensions#blockingscheduler – akarnokd Jun 20 '17 at 16:34

2 Answers2

16

For RxJava2 use "blockingSubscribe()"

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

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

Tassos Bassoukos
  • 16,017
  • 2
  • 36
  • 40