简体   繁体   中英

Rxjava2 blockingSubscribe vs subscribe

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.

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM