Start Your RxSwift Journey in Less Than 10 Minutes

RxSwift is well known for having a steep learning curve. But taking the time to learn it can easily be the next significant leap in your development abilities. We'll cover the basic concepts of the library to quickly get you up to speed.

Written by 

In order to fully understand the concepts behind RxSwift, we need to begin from the bottom. First off, let's learn about the programming paradigm reactive programming that RxSwift is based on.

Reactive Programming

What is reactive programming exactly? To put it briefly, it is to write your programs using asynchronous data streams. Your code becomes more centered around reacting to events that can occur at any point in time. Most frontend engineers already do some amount of reactive programming without realizing. For example, when a user decides to type letters into a text field, logic needs to be in place to handle the incoming stream of data.

You have probably heard of the GoF design pattern known as Observer pattern. In that pattern, we deal with the two objects subjects and observers. The subjects provide events that observers subscribe and react to. Same concept that reactive programming extends upon by dealing with entire streams of events that are handled by observers. This whole event-based process is simplified greatly by RxSwift. So let's take a closer look at it.

ReactiveX

RxSwift is part of the library called ReactiveX (or simply Rx). RxSwift is simply the implementation of the library in the Swift language. If you later decide to do web development, you can try out the JavaScript implementation called RxJS and still be familiar with the principles, operators and so on from Rx.

To understand the basics of RxSwift, we first need to look at two variable types Observables and Observers.

Observables and Observers

In the world of Rx, the terms Observables and Observers are what everything is built around. Let's break them down.

Observables are generics that you can make of any type you like. Defining observables can be done in different ways:

// just-operator will create observable containing a single item. 
// you can either type the Observable type out explicitly or let Swift infer the type. 
let firstObservable: Observable<String> = Observable<String>.just("my first observable") 

// of-operator will make an observable with items of each parameter. 
let secondObservable = Observable.of(1, 2, 3) 

// from-operator lets you pass an entire array. 
// each element inside the array will become individual items in the observable. 
let secondObservable = Observable.of(["this", "is", "awesome"])

Now we'll see how to make observers that subscribe (a.k.a. subscribers) to the items of the observables:

let integerObservable = Observable.of(1, 2, 3) 

integerObservable.subscribe({ item in
    print(item)
})

// Output:
// next(1)
// next(2)
// next(3)
// completed

When looking at the output, you're probably wondering what next and completed are. That's a stream of events, also an observable sequence. The three types of possible events emitted by an observable are:

  1. .next(value: T)
  2. .error(error: Error)
  3. .completed

First off, a next-event contains a value property which is a single item from the observable. The next-events are used to pass items to the observers/subscribers.

The completed-event and error-event are known as stop-events. This is because they define the end of an observable sequence. If the sequence ends normally, completed is emitted. If an error is encountered instead, the sequence is stopped as well.

Disposing Observers

We always want to make sure to cancel subscriptions in order to avoid memory leaks. Here are two ways you can do it:

let observer = integerObservable.subscribe({ item in 
    print(item) 
})

// method 1: calling the dispose method
observer.dispose()

// method 2: adding subscription to DisposeBag
let disposeBag = DisposeBag()
observer.disposed(by: disposeBag)

DisposeBag lets you add multiple subscriptions to it, and when it's deallocated, the subscriptions get canceled. As long as you remember to do, you're free to do it however you like.

Types of Subjects

Subjects are observables that let you add new items dynamically. They let us have observables sequences without a fixed amount of items.

Currently, RxSwift consists of three types of subjects which are:

  1. PublishSubject
  2. BehaviorSubject
  3. ReplaySubject

The PublishSubject won't store any previous emits. This means that subscribers only receive new emits. It will always start as empty.

The BehaviorSubject will remember the last emitted item. This item is emitted to any new subscribers. It will have an initial value that is emitted to subscribers when no previous item exists.

Lastly, the ReplaySubject is similar to BehaviorSubject but it lets you specify the amount of previous emits to remember. These are emitted to new subscribers. ReplaySubject will always start as empty.

Essential Operators

RxSwift is packed with plenty of different operators to save you time when you either want to filter, transform or combine items emitted by observables.

To get an overview of the essential ones, I have written three articles that cover these types of operators.

In case you want to see the entire list of operators available, check it out here.

Wrapping Up

We went through the absolute basics of RxSwift. Everything from creating observable, subscribing to them and disposing of your subscriptions. We also covered the attributes of the three different types of subjects. After looking at the additional resources to learn about operators, you should have a solid foundation. Now, to really get familiar with RxSwift, you need to get your hands dirty and start using it in your mobile applications.

Thanks for reading. Follow me on Twitter and share this article if you found it helpful.

Share this post

Facebook
Twitter
LinkedIn
Reddit

You may also like

Automation

iOS Continuous Integration Using Travis CI and Fastlane

Continuous Integration (CI) is a powerful practice to keep any app in a stable state throughout its development. Here’s how you set up CI for iOS apps to automatically perform code validation and testing whenever your code changes.

Design

How to Make Animated 3D Mockups in Seconds

As an individual app developer, you need to bring attention to your published apps. Companies of top-selling apps agree on how this is executed successfully. They create stunning and professional-looking animated 3D mockups of the apps. I’m here to tell you how you can create these for yourself in a matter of seconds.

Swift

7 Useful Filtering Operators in RxSwift

After using RxSwift for several months now, I can safely say that filtering is a key feature that has saved me plenty of lines of code. To know which filtering operators to use when, requires a basic overview, so let’s look at 7 of my favorite filtering operators this library has to offer.