I’ve been working on a Zhihu Daily client to evaluate RxJava’s benefits and trade-offs in a real project. RxJava has gained significant traction abroad, with language bindings spanning Java, JavaScript, C#, Scala, Clojure, C++, Python, Ruby, Kotlin, Swift, and more.
Reactive Extensions (Rx) is an event-based asynchronous programming framework built on the Observer pattern. It abstracts common concerns like thread scheduling, synchronization, thread safety, concurrent data structures, and non-blocking I/O.
For a great introduction, read RxJava for Android Developers (in Chinese) by Zhu Kai.
Schedulers
RxJava provides several Schedulers to control execution threads:
| Scheduler | Use Case | Notes |
|---|---|---|
Schedulers.immediate() | Current thread | Default – runs inline |
Schedulers.newThread() | Dedicated thread | Creates a new thread per subscription, no reuse |
Schedulers.io() | I/O operations | File/db/network. Cached thread pool with no cap. Reuses idle threads. Not for CPU-bound work |
Schedulers.computation() | CPU-bound work | Fixed pool sized to core count. Not for I/O |
AndroidSchedulers.mainThread() | Android UI thread | For UI updates |
Use subscribeOn() and observeOn() to control threading:
subscribeOn(): Specifies the thread for the source Observable (whereOnSubscribefires). Only the first call in the chain takes effect.observeOn(): Specifies the thread for downstream operators (whereSubscriberreceives events). Can be called multiple times, each switching threads for subsequent operations.
Creating Observables
| Operator | Description |
|---|---|
Create | Create Observable by calling observer methods programmatically |
Defer | Defer creation until subscription; fresh Observable per observer |
Empty / Never / Throw | Precise, limited-behavior Observables |
From | Convert arrays or Iterables into Observable |
Interval | Emit sequential integers at timed intervals |
Just | Convert object(s) into an emitting Observable |
Range | Emit a range of sequential integers |
Repeat | Emit items repeatedly |
Start | Emit return value of a function |
Timer | Emit single item after a delay |
Transforming Observables
| Operator | Description |
|---|---|
Buffer | Gather items into bundles periodically, then emit the bundle |
FlatMap | Transform each emission into an Observable, merge all results |
GroupBy | Divide Observable into groups by key |
Map | Apply function to each emission |
Scan | Apply function sequentially, emit each successive intermediate value |
Window | Like Buffer, but emits Observables instead of collections |
Currently building a real app with RxAndroid. While the basics are straightforward, real-world usage has nuances worth exploring. More to follow.