Observables and observers

Now that RxSwift is set up in our project, let's start with a few basic concepts before diving into some code:

One way to look at reactive extensions is as a mix of the iterator and observer design patterns. Now, while the former is intrinsically associated with a sequential, synchronous view of things, the latter is an asynchronous, callback-based paradigm. Rx acts as a bridge across those two worlds, ensuring you can go from one view to the other without losing any information. This property actually has a mathematical proof (https://repository.tudelft.nl/islandora/object/uuid:bd900036-40f4-432d-bfab-425cdebc466e/datastream/OBJ/download), and, although maybe not immediately interesting, this only adds to the beauty of the paradigm.

All of this can be translated into the following code snippet:

 let aDisposableBag = DisposeBag()
let thisIsAnObservableStream = Observable.from([1, 2, 3, 4, 5, 6])

let subscription = thisIsAnObservableStream.subscribe(
onNext: { print("Next value: \($0)") },
onError: { print("Error: \($0)") },
onCompleted: { print("Completed") })

// add the subscription to the disposable bag
// when the bag is collected, the subscription is disposed
subscription.disposed(by: aDisposableBag)
// if you do not use a disposable bag, do not forget this!
// subscription.dispose()

Usually, your view controller is where you create your subscriptions, while, in our example thisIsAnObservableStreamobservers and observables fit into your view model. In general, you should make all of your model properties observable, so your view controller can subscribe to those observables to update the UI when need be. In addition to being observable, some properties of your view model could also be observers. For example, you could have a UITextField or UISearchBar in your app UI and a property of your view model could observe its text property. Based on that value, you could display some relevant information, for example, the result of a query. When a property of your view model is at the same time an observable and an observer, RxSwift provides you with a different role for your entity—that of a Subject. There exist multiple categories of subjects, categorized based on their behavior, so you will see BehaviourSubject, PublishSubject, ReplaySubject, and Variable. They only differ in the way that they make past events available to their observers.

Before looking at how these new concepts may be used in your program, we need to introduce two further concepts: transformations and schedulers.