In RxJava 3, what is the difference between subscribeOn and observeOn, and what happens when a chain uses each of them twice?
answer
- one moves the start, one moves the rest
- subscription travels upstream
- nearest the source wins
- every observeOn is another hop
- io for blocking, computation for CPU
basics
~20 ssubscribeOn picks the Scheduler on which subscription, and so a cold source's work, starts; with several, the one nearest the source wins. observeOn switches the thread for everything below it, and each extra observeOn adds another hop.
solid answer
~40 s`subscribeOn` changes the thread on which subscription travels up the chain, so it decides where a cold source such as `Single.fromCallable` does its work. Its position in the chain does not matter, and when there are several, the one nearest the source decides. `observeOn` changes the thread for everything downstream of it: it queues signals and replays them on the new `Scheduler`, so each `observeOn` is another thread hop. The Android shape is `subscribeOn(Schedulers.io())` for blocking I/O and `observeOn(AndroidSchedulers.mainThread())` just before the UI callback. `Schedulers.io()` grows its pool as needed and suits blocking calls; `Schedulers.computation()` is sized to the CPU count and suits CPU work. Time-based operators such as `debounce` and `delay` emit on `computation()` by default, so they need an `observeOn` after them before touching views.
code
kotlin · 13 linesimport io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Single
import io.reactivex.rxjava3.schedulers.Schedulers
import java.io.File
fun loadReport(file: File): Single<String> =
Single.fromCallable { file.readText() } // runs on an io() thread
.subscribeOn(Schedulers.io()) // nearest subscribeOn to the source: it decides
.map { raw -> raw.lines() } // still on that io() thread
.observeOn(Schedulers.computation()) // hop 1
.map { lines -> "${lines.size} lines" } // runs on a computation() thread
.subscribeOn(Schedulers.single()) // no visible effect on where fromCallable runs
.observeOn(AndroidSchedulers.mainThread()) // hop 2: the subscriber runs on the main threadgo deeper
Remember the usual Android pair: subscribeOn(Schedulers.io()) for the background work and observeOn(AndroidSchedulers.mainThread()) just before updating the UI.
Explain that subscribeOn acts on the upward subscription and observeOn on the downward signals, and why repeating each of them behaves so differently.
Diagnose wrong-thread bugs from the chain alone: time-based operators on computation, hot subjects ignoring subscribeOn, blocking calls starving the computation pool.
Set team conventions: whether repositories or callers own threading, injectable schedulers for tests, and a rule against blocking work on the computation pool.
## Two operators, two directions An RxJava chain carries two kinds of traffic. **Subscription** travels *up*: when you call `subscribe()`, each operator subscribes to the one above it until the source is reached and starts producing. **Signals** (`onNext`, `onError`, `onComplete`) travel *down* from the source to your callback. RxJava 3 has one operator for each direction: - `subscribeOn(scheduler)` moves the **upward** subscription onto a `Scheduler`, so the source starts its work there. - `observeOn(scheduler)` moves the **downward** signals onto a `Scheduler` from that point on. Without either, and without time-based operators, everything runs on the thread that called `subscribe()`, or on whatever thread the source happens to emit from. ## subscribeOn: where the work starts - It affects the source and every operator between the source and the first `observeOn` below it. - Its position does not matter: `subscribeOn` at the bottom of the chain still moves the work at the top. - With several `subscribeOn` calls, the one **nearest the source** decides where a cold source runs. The others only move the subscription step through the operators between them, which you rarely notice. - It does not move a **hot** source's emissions. A `PublishSubject` emits on whichever thread calls `onNext`, regardless of where the subscription happened. ## observeOn: where the results go next - It affects every operator and callback **below** it, never above. - It works by queueing signals and draining them on the target `Scheduler`, so each `observeOn` is a real thread hop with a queue. - Several `observeOn` calls are normal: each switches the thread for the next segment of the chain. - Each hop costs a queue and a thread handoff, so bouncing between schedulers for trivial `map` steps adds latency without benefit. - On Android, the last one before UI code is `observeOn(AndroidSchedulers.mainThread())`, which comes from the RxAndroid library, not from RxJava itself. ## Using each one twice | Chain | Effect | |---|---| | `subscribeOn(A)` then `subscribeOn(B)` lower down | the source runs on A; B is effectively invisible | | `observeOn(A)` then `observeOn(B)` lower down | operators between them run on A, everything after the second on B | | `subscribeOn(A)` then `observeOn(B)` | source and early operators on A, the rest on B | ## Choosing a Scheduler | Scheduler | Pool | Use it for | |---|---|---| | `Schedulers.io()` | cached, creates threads as needed, can grow without bound | blocking I/O: files, sockets, database calls | | `Schedulers.computation()` | fixed, one thread per available CPU by default | CPU work: parsing, sorting, diffing | | `Schedulers.single()` | one shared thread | work that must run strictly in order | | `Schedulers.trampoline()` | the current thread, queued | tests and recursion, not background work | | `AndroidSchedulers.mainThread()` | the Android main thread (RxAndroid) | touching views and UI state | Two rules follow from the pool shapes. Blocking calls on `computation()` can occupy every one of its few threads and stall unrelated work, including the timers behind `debounce`, `interval` and `delay`. Heavy CPU loops on `io()` are not dangerous in the same way, but they let the pool grow with threads that fight over the same cores. ## Traps on Android 1. **Time-based operators change the thread.** `debounce(300, TimeUnit.MILLISECONDS)`, `delay`, `interval` and `timer` without an explicit `Scheduler` emit on `Schedulers.computation()`. Updating a view after them without an `observeOn(AndroidSchedulers.mainThread())` throws Android's `CalledFromWrongThreadException`. 2. **observeOn too early.** Moving to the main thread before a heavy `map` puts that work on the main thread and drops frames. Hop to the main thread as late as possible. 3. **subscribeOn on a subject.** It does not move the subject's emissions; use `observeOn` after the subject to move processing off the thread that feeds it. 4. **Hard-coded schedulers in tests.** Inject schedulers, or override them with `RxJavaPlugins.setIoSchedulerHandler` and `setComputationSchedulerHandler`, so tests can run on `Schedulers.trampoline()` or a `TestScheduler`. ## Summary `subscribeOn` answers "where does the work start", and only the one nearest the source matters. `observeOn` answers "where do the results go from here", and every one of them counts. A common convention is to let the layer that does the blocking work choose its `subscribeOn`, and to let the UI layer add the final `observeOn(AndroidSchedulers.mainThread())`, so each decision lives next to the code that needs it.
- A PublishSubject is fed from the main thread and its chain has subscribeOn(Schedulers.io()). Where do the map lambdas run?On the main thread. `subscribeOn` only moves the act of subscribing; a subject is hot and emits on whichever thread calls `onNext`, so items arrive on the main thread anyway. To move the processing, add `observeOn(Schedulers.computation())` or `observeOn(Schedulers.io())` after the subject.
- Why should blocking I/O not run on Schedulers.computation()?`computation()` is a fixed pool sized to the number of available CPUs, shared by every chain that uses it and by the timers behind `debounce`, `interval` and `delay`. A few blocking calls can occupy all its threads and stall unrelated work. `Schedulers.io()` creates threads as needed, which suits blocking waits.
- A chain with debounce crashes with CalledFromWrongThreadException when it updates a TextView. Why?`debounce` without an explicit `Scheduler` emits on `Schedulers.computation()`, so everything after it runs off the main thread. Add `observeOn(AndroidSchedulers.mainThread())` after the debounce and any background work, immediately before the code that touches views.
- subscribeOn only affects the operators written after it in the chain.
- A second subscribeOn lower in the chain moves the source onto the new Scheduler.
- observeOn changes the thread for the whole chain, upstream included.
- Schedulers.io() and Schedulers.computation() are interchangeable thread pools.
- subscribeOn(Schedulers.io()) moves a subject's emissions off the main thread.