Create and Chain Observable Sequences in RxSwift
Shorten your code and make it more efficient
In this short tutorial, we will learn how to create two RxSwift’s
Observable sequences and chain them.
The example app shows a
UITextField at the top of the screen. It waits for a user input, and when a user has inputted five letters containing “rx”, the
UITextField flashes green and refreshes:
The source code of the project is available on GitHub.
First, let’s quickly create and position our
textField on the screen:
Now, add the following imports at the top of the file:
import RxSwiftimport RxCocoa
We have to add the
disposeBag property to deallocate subscriptions in the future:
private let disposeBag = DisposeBag()
We are ready to create our sequences now.
Create Observable Sequences
Let’s start with the first task: finding “rx” in the inputted string:
We will call this searching method after a user inputs a letter. If it succeeds, it will emit a
true value. If not, the
false value will be emitted instead.
To create a method for the second task, animating and clearing the
textField , we write the following code:
As we can see, this method performs a short 0.2-second animation that changes the
backgroundColor property of the
textField. On completion, we perform another animation, returning the
backgroundColor to its former state and emit the
true event onto the
Now it is time to chain these brand-new observables.
We need to create a method that will hold bindings for the
Here is the breakdown of what happens in this method:
- Using the
.orEmptymethod, we transform the optional
- We filter out all events where the
textField’s text count is not equal to five. When it is equal to five, we perform the
.flatMapmethod changes the type of the sequence from
Observable<Bool>, because this is the type that the
findSubstring(in: )method returns.
- We only allow
trueevents to pass next, meaning that the “rx” substring was found.
- In the next
.flatMapmethod, we animate the
textFieldand return a new sequence of type
Observable<Bool>, which emits a
trueevent on the completion of the animation.
- When the animation is completed, we pass the
.subscribe, we simply print “Subscribed” to debug the implementation.
- Finally, we add the subscription to the
disposeBagthat will deallocate it.
Do not forget to add the
bindTextField() method to the
We have successfully created and chained observable sequences.
ViewController.swift file now looks like this:
We have seen how easy it is to chain different observable sequences using the
.flatMap function. If you are curious to learn more about what you can do with RxSwift, feel free to check out my other relevant pieces:
Reactive MVVM and the Coordinator Pattern Done Right
With Swift 5, RxSwift, and RxDataSources
How to Implement UITableView and UICollectionView With RxDataSources
And why you will never directly use UITableViewDataSource again
Thank you very much for reading!