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.
Start Your RxSwift Journey in Less Than 10 Minutes
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:
- .next(value: T)
- .error(error: Error)
- .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:
- PublishSubject
- BehaviorSubject
- 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
How to Generate API Client Code in React (Native) Apps
Keeping your API client code updated whenever there’s a change in the back-end rest apis and models is tedious and error prone as a front-end developer. A better way would be if the API client code was kept updated automatically so you have one less thing to worry about.
Swift
Transforming Operators in RxSwift: map, flatMap & flatMapLatest
Transforming operators in RxSwift serve the purpose of preparing data coming from observables before it reaches the subscribers. Let’s cover this type of operators and look at 3 operators you will be using all the time.
DevOps
3 EAS Pipelines for Deploying React Native Apps in Teams
One of the best ways to increase productivity in a react native project is to automate the process of deploying builds you want to share internally in your team or with actual costumers via the app store. And you might be surprised at how easy it can actually be implemented when you have the right set of tools like GitHub Actions and EAS.