Rxjava2 blockingSubscribe vs subscribe
Asked Answered
S

1

6

I have read the explanation about blockingSubscribe() and subscribe() but neither I can write nor find an example to see the difference of these. It seems that both of these work the same way. Could someone provide an example of these 2, preferably in Java.

Swaziland answered 10/1, 2019 at 11:50 Comment(0)
C
12

blockingSubscribe blocks the current thread and processes the incomnig events on there. You can see this by running some async source:

System.out.println("Before blockingSubscribe");
System.out.println("Before Thread: " + Thread.currentThread());

Observable.interval(1, TimeUnit.SECONDS)
.take(5)
.blockingSubscribe(t -> {
     System.out.println("Thread: " + Thread.currentThread());
     System.out.println("Value:  " + t);
});

System.out.println("After blockingSubscribe");
System.out.println("After Thread: " + Thread.currentThread());

subscribe gives no such confinement and may run on arbitrary threads:

System.out.println("Before subscribe");
System.out.println("Before Thread: " + Thread.currentThread());

Observable.timer(1, TimeUnit.SECONDS, Schedulers.io())
.concatWith(Observable.timer(1, TimeUnit.SECONDS, Schedulers.single()))
.subscribe(t -> {
     System.out.println("Thread: " + Thread.currentThread());
     System.out.println("Value:  " + t);
});


System.out.println("After subscribe");
System.out.println("After Thread: " + Thread.currentThread());

// RxJava uses daemon threads, without this, the app would quit immediately
Thread.sleep(3000);

System.out.println("Done");
Clan answered 10/1, 2019 at 13:5 Comment(2)
So, it runs the Observer's actions in the main Thread the current function (main()) was running?Swaziland
@LiTTle, yes, I just checked.Coinage

© 2022 - 2024 — McMap. All rights reserved.