Now that RxSwift is set up in our project, let's start with a few basic concepts before diving into some code:
- A stream in SwiftRx is represented through Observable<ObservableType>, which is equivalent to Sequence, with the added capability of being able to receive new elements asynchronously.
- An observable stream in Rx can emit three different events: next, error, and complete.
- When an observer registers for a stream, the stream begins to emit next events, and it does so until an error or complete event is generated, in which case the stream stops emitting events.
- You subscribe to a stream by calling ObservableType.subscribe, which is equivalent to Sequence.makeIterator. However, you do not use that iterator directly, as you would to iterate a sequence; rather, you provide a callback that will receive new events.
- When you are done with a stream, you should release it, along with all resources it allocated, by calling dispose. To make it easier not to forget releasing streams, SwiftRx provides DisposeBag and takeUntil. Make sure that you use one of them in your production code.
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 thisIsAnObservableStream, observers 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.