RxSwift for Beginners: Part 1

We build professional apps for Android, iOS and mobile web.
Have a look

Reactive programming isn't a new concept. Rx has been around for a while now. RxSwift has emerged recently and now we can update in real-time with Swift!

This blog will cover the basics of RxSwift.

It's vital to understand the Observer pattern. I will summarise as simply as possible. The pattern contains an observable (an object) that is listened to by other objects called observers. The observable will post updates to the observers who are listening to it.

If a microwave is an observable, then anyone in the room is an observer. It will beep when it is done, and we will hear the beep and act accordingly to the notification.

Rx observables can do a number of things. RxMarbles is a great site to visualise the numerous functions of observables.

One example is debounce. This operator produces a value as long as no other value has been produced in a given length of time. For example:

systemObservable.debounce(3.0,  
 scheduler: MainScheduler.sharedInstance)
   .subscribeNext { [weak self] systemObservable in    
self?.updateSystem() }  
   .addDisposableTo(disposeBag)

If it seems intimidating - don't panic. I'll decipher this bit by bit. Firstly we have our behaviour subject 'systemObservable' which is an observable that holds a value. This value can change. We can ask for the value at any time by using value().

We are calling debounce on our observable to obtain the latest event in the last three seconds. Imagine a user spamming the power button of your app. This will trigger the sequence for the systemObservable. We could send all these events coming through - off, on, off, on, off. Or we could send just one, final one. They finally decide they want the system on. After 3 seconds that last event will be captured, instead of all of the events before that.

subscribeNext() will allow us to do something once the event has passed through debounce. So we are saying: record the latest event if nothing else has happened in the past 3 seconds, and then do __. We are subscribing to our observable, listening for the next event passed through.

Now that we get to act on the notification, we might want to update the system updateSystem().

Lastly, we add the sequence to a disposable bag to release resources (disposeBag is just a DisposeBag()).