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:

SchedulerUse CaseNotes
Schedulers.immediate()Current threadDefault – runs inline
Schedulers.newThread()Dedicated threadCreates a new thread per subscription, no reuse
Schedulers.io()I/O operationsFile/db/network. Cached thread pool with no cap. Reuses idle threads. Not for CPU-bound work
Schedulers.computation()CPU-bound workFixed pool sized to core count. Not for I/O
AndroidSchedulers.mainThread()Android UI threadFor UI updates

Use subscribeOn() and observeOn() to control threading:

  • subscribeOn(): Specifies the thread for the source Observable (where OnSubscribe fires). Only the first call in the chain takes effect.
  • observeOn(): Specifies the thread for downstream operators (where Subscriber receives events). Can be called multiple times, each switching threads for subsequent operations.

Creating Observables

OperatorDescription
CreateCreate Observable by calling observer methods programmatically
DeferDefer creation until subscription; fresh Observable per observer
Empty / Never / ThrowPrecise, limited-behavior Observables
FromConvert arrays or Iterables into Observable
IntervalEmit sequential integers at timed intervals
JustConvert object(s) into an emitting Observable
RangeEmit a range of sequential integers
RepeatEmit items repeatedly
StartEmit return value of a function
TimerEmit single item after a delay

Transforming Observables

OperatorDescription
BufferGather items into bundles periodically, then emit the bundle
FlatMapTransform each emission into an Observable, merge all results
GroupByDivide Observable into groups by key
MapApply function to each emission
ScanApply function sequentially, emit each successive intermediate value
WindowLike 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.

References