Understanding RxJava2: Core Concepts, Thread Scheduling, Backpressure, Transformers, and Hot vs Cold Observables
This article provides a comprehensive overview of RxJava2 for Android, covering its observer types, backpressure strategies, thread‑scheduling transformers, the compose() operator, differences between compose and flatMap, and the distinction between hot and cold observables with practical code examples.
RxJava2 is a reactive programming library for Android based on the observer pattern, enabling chainable operations on event streams.
The article introduces the five basic Observable types—Observable, Flowable, Single, Completable, and Maybe—detailing their behavior, typical use cases, and how they differ in data emission and completion semantics.
It then explains Transformers and the compose() operator as a means to encapsulate reusable logic such as thread scheduling, showing why they are preferable to repetitive code.
Example of a typical RxJava2 chain without abstraction:
Observable.from(someSource)
.map(new Func1
() {
@Override
public Data call(Data data) {
return manipulate(data);
}
})
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1
() {
@Override
public void call(Data data) {
doSomething(data);
}
});A helper method that applies thread scheduling using subscribeOn and observeOn :
Observable
applySchedulers(Observable
observable) {
return observable.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread());
}Using compose() to apply the transformer keeps the chain fluent:
Observable.from(someSource)
.map(new Func1
() { ... })
.compose(this.
applySchedulers())
.subscribe(new Action1
() { ... });The article compares compose() with flatMap() , noting that compose() operates on the whole stream and is executed immediately, whereas flatMap() processes each emitted item separately and may incur performance overhead.
It also clarifies the concepts of Hot and Cold Observables: Cold observables start emitting only after subscription, while Hot observables emit regardless of subscribers, with publish/replay converting Cold to Hot and Subject/Processor providing alternative mechanisms (the latter supporting backpressure).
Finally, the article briefly describes the publish/replay operators that turn an Observable into a ConnectableObservable and the role of Subjects/Processors as both observers and observables, enabling the transformation of Cold streams into Hot streams.
Sohu Tech Products
A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.