Skip to content

Instantly share code, notes, and snippets.

@tir38
Last active February 6, 2020 16:35
Show Gist options
  • Save tir38/dec52dc0b8259e1441b866a6b9accb9f to your computer and use it in GitHub Desktop.
Save tir38/dec52dc0b8259e1441b866a6b9accb9f to your computer and use it in GitHub Desktop.
import io.reactivex.Observable
import io.reactivex.schedulers.Schedulers
/*
What is blockingSubscribe() doing?
1. processing items on computation thread; not blocking main thread
2. processing items on computation thread; blocking main thread until terminal event
3. processing items on main thread; but not actually blocking main thread
4. processing items on main thread and blocking main thread until terminal event
*/
fun test() {
println("Starting on: " + Thread.currentThread().name)
Observable.just(1, 2, 3)
.doOnSubscribe { println("Subscribing on thread: " + Thread.currentThread().name) }
.subscribeOn(Schedulers.io())
.doOnNext { println("Observing stream on thread: " + Thread.currentThread().name) }
.observeOn(Schedulers.computation())
.doOnNext { println("Jumped to thread: " + Thread.currentThread().name) }
.blockingSubscribe { println("onNext, on thread: " + Thread.currentThread().name) }
println("Ending on: " + Thread.currentThread().name)
}
/*
Answer:
#4,
Not only is it blocking main thread (which I knew);
it's also processing items on the main thread, despite the observeOn() call.
Starting on: main
Subscribing on thread: RxCachedThreadScheduler-1
Observing stream on thread: RxCachedThreadScheduler-1
Observing stream on thread: RxCachedThreadScheduler-1
Observing stream on thread: RxCachedThreadScheduler-1
Jumped to thread: RxComputationThreadPool-1
Jumped to thread: RxComputationThreadPool-1
Jumped to thread: RxComputationThreadPool-1
onNext, on thread: main
onNext, on thread: main
onNext, on thread: main
Ending on: main
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment