RxJava uses a chain call design similar to the Stream API , providing filter, map, observeOn and other common operators . Unlike the Builder pattern, which does not require any order of method calls, RxJava’s operator calls need to maintain sequential relationships. A typical chain call scenario is as follows.
The chain call is triggered from subscribe()
and we look at the corresponding source code.
|
|
You can see that subscribe()
actually calls the concrete implementation of subscribeActual()
. The subclasses of Observable are ObservableFilter, ObservableMap, ObservableObserveOn, and so on. As you must have thought, these subclasses are obviously related to the corresponding operators. Take filter as an example.
As you can see, each filter call wraps the upper-level Observable into a new ObservableFilter, and so on, so that the call stack in our original example actually looks like this:
|
|
Here, the principle that RxJava chain calls can still maintain sequential relationships is clear. As for how each Observable is implemented, I won’t expand here, it involves Java’s static proxy, so you can Google it yourself if you are interested.