RxSwift Study Notes

2020, Jun 22    

Due to two of my recent projects heavily used RxSwift framework and the popularity of the framework in the community, I decided to spend my spare time in the weekend to have a thorough study on the project itself. As the name implies, the RxSwift framework is the swift implementation of the famous ReactiveX API standard. It is purely event driven and follows functional programming paradigm, serving as an excellent glue layer in common architectural design patterns like MVVM.

This article is the summary of core data structures of RxSwift and how the core models work together in an event subscription chain.

Core Models

The core concepts of RxSwift is quite simple: an observable(or multiple observables) which can dispatch events, an observer(or multiple observers) to recieve the events, and the operators in the middle to manipulate the events between the observables and observers, as well as subjects serving as relays to cache events and other utilities which make the framework easier to use (such as schedulers and traits). All of the concept I mentioned above are welly described in the RxSwfit github documents. After spending a whole day in reading through the source code, I eventually drafted a summary of the class diagram of the core models below:

The Producer and the Sink are the base pattern for all operators, which constructs of a large percentage of the project (I guess more than 70% of source code). The producer wraps the original observable, and pass the event to the specific type of sink owned by the producer, the sink further process the event based on the producers internal logic and forward it to the observer (or next layer of producer).

The simplified flow of how subscription is triggered across layers of operators and how the event is passing down from layers of operators are depicted as below:

As apple’s official framework Combine gradually gain its popularity in the community while serving as a similar functionality as compared to RxSwift. iOS developers may start to wonder how to make a choice between the two framework, in the short term, RxSwift is a battle proved solution and it will definitely win the heart of the majority group of developers. But as the maturity of Combine framework increases as furture iterations goes on, it seems there is no reason to refuse a embeded library when its usability matches the open source alternative. Even the author of the RxSwift admit that RxSwift will gradually be replaced by Combine.

TOC