Reactive Programming in Swift is getting a lot of attention these days, specially with the launch of RxSwift Reactive Programming with Swift book. I decided to try out RxSwift using by implementing a small project.
The project comprises of two screens. A table view, which displays a list of tasks and a add new task screen. The add new task screen is displayed as a model on top of the tasks list screen. Let’s see how RxSwift can be used to create this app.
Populating the Tasks in Table View Control:
The first task is to display tasks in a table view control. Instead of declaring tasks array as a default array we have to create it as an array that can be observed. This is accomplished by the Variable type as shown below:
As indicated above tasks is an array which can hold items of type Task. The magic ingredient is the Variable type which makes our tasks array observable.
Next, we are going to bind our tasks array to the table view. This means whenever tasks array is altered, table view automatically updates to reflect the changes. You can also say that the tasks array and table view rows will be in sync.
Thats it! The last line adds a new task to the tasks array, which automatically invokes the bind function on the tasks observable allowing the table view to automatically update and reflect the new row.
Make sure that the cell identifier on the Storyboard is set to “Cell” .If you run the app you will notice that the table view now displays a single task.
You did not have to implement any of the delegate functions of the UITableView or UITableViewDataSource. Everything is hooked up behind the scenes by RxSwift.
Adding New Task to Table View:
We will display the “TaskDetailsViewController” in a model, when the user presses the bar item button in the navigation bar. Since, we will not be using any delegates or blocks to pass the data back to the presenter, this code can become a little longer as shown below:
The throttle is simply making sure that we don’t trigger the tap in quick succession. Inside the subscribe block we get the task details view controller using the storyboard identifier. The TasksDetailsViewController class exposes a property called task which is of type PublishSubject. PublishSubject is a special type in RxSwift which can act as both observer as well as subscriber. The implementation for TaskDetailsViewController is shown below:
Selecting the TableView Row:
RxSwift provides a lot of helper functions to work with the UIKit controls. These helper functions are part of the RxCocoa framework.
The heart of the above function is the modelSelected helper function, which is triggered whenever you select a UITableView row.
The demo is shown below:
You can download the complete source code here.