ABC to populating a List with RxSwift
There are a lot of articles on RxSwift, and it has sworn to popularity recently because it helps us to build our apps differently. When we think reactive, we think of both UI and data. When data change, UI changes. As simple as that!
I am going to bring you through an ABC example to get the idea of RxSwift and that’s it!
UITableView is one of the most used UI components in iOS apps. You will learn how to apply RxSwift (with RxCocoa) in this short tutorial, and populate a tableview with some data.
1. Setup Xcode Project
Assuming you are starting this tutorial fresh, launch Xcode (I am using Xcode 11) and create a new project. In your
Main.storyboard , add a
ViewController and add one prototype cell. Give it a
Basic style and fill the
Remember to connect an outlet to your
@IBOutlet weak var tableView: UITableView!
2. Install RxSwift & RxCocoa via Cocoapods
Launch Terminal and
cd to your project’s root directory. Next, init Pod:
Then, add the pods into
Podfile and do an install:
vim podfilepod 'RxSwift', '~> 5'
pod 'RxCocoa', '~> 5'pod install
Now you have your project and pods setup! Let’s start doing some reactive programming all in
Yes, the first step is to Add Data, use static data here for simplicity and of type BehaviorRelay, which is a variable in the reactive world. It helps us to establish Observable and Observer relationship later when the UITableView binds its UI with this Data.
It’s a good practice to always have a
DisposeBag to manage memory. Though it’s not really necessary here, for good practise, I still created it.
Bind Data to View
Do this in
Connect to Simulator/Device
To see it in action, just run your code! You should now see a list of data populated in just a few lines of code!
In this short tutorial, you may now realize that you no longer need to:
- Connect Delegate
- Connect Datasource
- Implement Number of Rows
- Implement Cell For Row
All these are taken care of in the reactive paradigm, and that is really the beauty of it. Apple realized this and came out with SwiftUI and Combine. Personally, I still believe RxSwift is good enough for most projects, but please feel free to explore both RxSwift and Combine, and do let me know which you prefer.
I am planning my next write up on RxTest, so stay tuned!
Thank you for reading!