RxSwift first steps, roadmap and resources!

The journey through the RxSwift universe is something vast that begins with a much broader concern, the reactive way of thinking, which is a shift in our programming mindset. Reactive programming is a topic that requires understanding for proper use, so the road for this kind of knowledge needs to start with core concepts as well as the motivation behind this different approach to programming. This post is a sort of entrance ticket for this reactive club, but the swift and iOS session of the party.

Recently I’ve started to write some stories for a blog called Tech Beacon. This story is the first one that got published. Hope you guys enjoy. =)

Roadmap

As stated in the disclaimer no post could contain all the information needed to understand and apply RxSwift with confidence. This session outlines some key resources that will help you understand some of the big ideas behind reactive programming and its implementation in RxSwift.

  • Ray Wanderlich’s RxSwift book. This book is by far, the best resource that I have ever bumped in throughout my searches. A must have for anyone who would like to understand and apply RxSwift.
  • Reactive Programming talk by Objc.io’s Swift Talks. Objc.ios swift Talks is known by its amazing content. This video is the first addressing RxSwift.
  • Official Site of RX frameworks.
  • RxSwift GitHub page.
  • Marble Diagrams, a beautiful way to understand sequences and transformations that happen over time.

Disclaimer: No single post is big enough to teach you RxSwift or reactive programming. My approach with this tutorial is to create a roadmap, showing resources and initial “how to”s, modules of your app that are more suitable to become reactive and so on.

Approach

Applying RxSwift to your project is not something you should be doing with an All-in strategy. The best approach is to find some isolated part of your app and migrate it to reactive, and then weight the benefits, differences, advantages or disadvantages of this new approach.

There is a guideline below, sorted in order of difficulty from easy to more challenge. This roadmap shows parts of your system that are suited to get some RxSwift. =)

  • UI components. Observe changes in UI components and respond to them. Forget about delegates!
  • Replacing TableView and CollectionView’s data sources with RxSwift.
  • Sharing information between controllers and different objects using observables
  • Create a Reactive Network layer, using observables instead of callbacks.
  • Create your own Reactive extensions. Wrap delegation using Observables, provide Reactive Extensions for system classes.

In this post, I will focus on the entry level, so I will only address the first step of the above list. You guys can download the code for this post here.

Before diving into theory and understand some of the core concepts, lets see RxSwift in action first.

This example will cover how to observe and react to changes in two different UISliders, using both the reactive and nonreactive approach.

Non Reactive

The nonreactive version introduces something subtle but with the potential to cause a lot of harm, mutation. Mutation by it self is not an evil being. However most of the time it is accompanied by its evil brother, side effects. That said, let’s go back to our example. To be notified of a big sale! We had to create an instance variable to store the last price and last unit. Doing so introduces mutation and the possibility of side effects in our code. Side effects and global variables can produce some of the most difficult to track problems in software development. As well as lots of headaches.

Reactive

The reactive version allows us to create observers to react upon emitted events on our observables; we can even combine two different observables and do a few transformations and filters on the emitted values, only reacting if the result is in the expected range. The best thing is that we did all that without mutation or side effects. The reactive approach limits mutation and side effects making easier to evolve and maintain the system.

But, wait a minute. What is an observable?

An observable is something that can asynchronously produce or emit a sequence of events over time. Other classes known as observers can subscribe(register) to this emitted events and react to them.

The definition sounds ok, but why should I care? And why would I want to use this Observable kind of thing? To answer this two questions, we need to go back a little and bring some context.

Synchronous x Asynchronous

There are two types of code, synchronous and asynchronous. The first one is very intuitive, and programming with it feels like the way we think, step by step, one thought after the other and so on.

let file = readFile()
print(file)

The second type of code, the asynchronous one is not so trivial and working with it many times can be very challenging. Callbacks, delegation, closures are a few different techniques used to work with async code, but sometimes they feel a little verbose. Reactive programming is another way of working with asynchronous code.

readFile() { file in

}
print(“This will be executed before the return of the file”)

Reactive programming is an asynchronous programming paradigm concerned with data streams and the propagation of change over time.

The evolution of technologies created an expectation that applications and systems, in general, should have a certain level of responsiveness. Freezing the user screen to do some processing under the hood is something unacceptable nowadays. Therefore, today more than never our code is becoming more and more asynchronous. RxSwift is a library that can help us with that.

In our example, we created an observable of Floats that emits a new value every time the price slider’s value change.

priceSlider.rx.value
.asObservable()

We can react to it through subscription, which is another way of saying: Hey sequence, I am interested in your events!

priceSlider.rx.value
.asObservable()
.subscribe(onNext: { newValue in
print(newValue)
})

The gist URL shows a little different implementation. Its version executes first an operation called map, which is a sort of transformation of the data that is later bound to the text label. Bind is another way of doing a subscription, sending the emitted events to an observer. In this case:

priceLabel.rx.text

Another important thing to know about observables is that they do not start to send events until someone subscribes to them. Observables are sequences and subscribing to them is more like calling next() in the first element of the sequence. Observables will continue to emit events after its initial subscription until they emit an error or a completed event and only then they are terminated. Of course, we can manually terminate an observable by calling dispose() on it. Manually “disposing” every Observable would be terrible, so we have an easier way to do it, using DisposeBags. DisposeBags are responsible for holding Disposable references, later when the “bag” is about to be deallocated, it will call dispose() on every reference.

Now we can understand the following code:

.bind(to: priceLabel.rx.text)
.addDisposableTo(disposeBag)

Enough said ..

There is still a lot to learn about observables and how to create them, interact, transform and so on. RxSwift has many other concepts that needed to be acquired in order to navigate it with confidence. The next important concept is Subjects. Subjects are both observables and observers at the same time, which means they not only emit events but can subscribe, and react to other observables. Observables, Subjects, and transformations together will provide the basic RxSwift toolkit that you will need to handle 80% of the job. As mentioned early there is no way to convey all this information in a single post, my goal here is to provide the most fundamental knowledge, the first building block of a much bigger reactive wall, and of course share with you guys a path, a roadmap of resources to become a better reactive programmer.