FRP with RxSwift examples (#1)

TuyenBQ
5 min readAug 28, 2016

--

Nowadays, Reactive programming is not quite strange with devs world in many languages. For this blog, it will be focusing to Swift and a strength library by ReactiveX corporation, absolutely is RxSwift, the grew up language for 2 years ago. If you’re already familiar with the concept of FRP, skip ahead to the next example. Regarding FRP concepts, kindly to dive in to my 2 previous blog: this one and another one.

If you even don’t have time to read on 2 my blogs, here is a brief FRP was:

Even before Swift was announced, Functional Reactive Programming (FRP) has seen a tremendous rise in popularity in recent years versus Objected Oriented Programming. From Haskell to Go to Javascript, you will find FRP-inspired implementation. Why is this? What’s so special about FRP? Perhaps most importantly, how can you make use of this paradigm in Swift?

Functional Reactive Programming is a programming paradigm that was created by Conal Elliott. His definition has very specific semantics and you are welcome to explore them here. For a more loose/simple definition, Functional Reactive Programming is a combination of two other concepts:

Reactive Programming, which focuses on asynchronous data streams, which you can listen to and react accordingly. To learn more, check out this great introduction.

Functional Programming, which emphasizes calculations via mathematical-style functions, immutability and expressiveness, and minimizes the use of variables and state. To learn more, check out our Swift functional programming tutorial.

An example

One of the worthy examples to demonstrate that FRP’s effects seems like Search something with a combination between UITableView and UISearchBar. To getting started, we need a podfile to get all and your dependencies:

To be done, we have these things:

Next, the UI will be like:

That’s pretty for preparation, now let’s write code. Suppose you want to find one or more IT companies at your city. Make a dummy companies as much as you could. Also, you could make an API to response worth data, but pls avoid to do that, because we not needed and never focused on it, taking time ever. The dummy data such as:

var foundCompanies = [String]()let companiesDummy = [“Apple Inc”, “Microsoft Co.,”, “Nokia”, “Yahoo”, “Snapchat”, “Twitter”, “Facebook”, “Google”, “Bings”, “FPT Software”, “Framgia”]

Here we go! and then, we’re going to setup an extension tableview’s datasource be like:

  • Drag and drop tableview, searchBar references:
@IBOutlet weak var searchBar: UISearchBar!
@IBOutlet weak var tableView: UITableView!
  • Make an extension to implement datasource:
extension ViewController: UITableViewDataSource {   func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return foundCompanies.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(“companyCell”, forIndexPath: indexPath)
cell.textLabel?.text = foundCompanies[indexPath.row]
return cell }}

Compile and run, this app shows nothing. Yes, it does right the way. By the traditional way we did with normally. Steps to show the result always is:

  • Conform search bar delegate, when user pressed anything, the delegation will be given specified character and fall into the delegation function
  • You got it and using loop and if-else conditions to throughout elements and filter the matched result and display on screen.

→ It had made a huge line of code in your project and complex logic on each of line code. So simply, we would use to Rx:

searchBar
#1 .rx_text
#2 .throttle(1.0, scheduler: MainScheduler.instance)
#3 .distinctUntilChanged()
#4 .filter { $0.characters.count > 0 }
#5 .subscribeNext { [unowned self] (com) in
self.foundCompanies = self.companiesDummy.filter { $0.hasPrefix(com) }
self.tableView.reloadData()
}
#6 .addDisposableTo(disposeBag)

OK, looks like quite interesting, hud? We will step by step above code snippet.

  • #1 shows us the property of search bar UI, which supported by RxCocoa(is extension of RxSwift). It emits signals once the text in the search bar change. In fact, we’re observing the text in the search bar.
  • #2: throttle() makes the delay effect on given scheduler. It means the request will be sent after 1 second. It is to avoid the same sending request when user enter the same character very fast. To do that without Rx we would add some flags searched query and compare it with the new one, it make us mad.
  • #3: distinctUntilChanged() protects us from the same values.
  • #4: filter is to avoid empty sending request, whether user enter empty character or not.
  • #5: subscribeNext is probably quite understandable — we are subscribing to the observable property, which produces signals. And it will show you everything new. In our case we need only new values, but subscribe has more wrappers with events like onError, onCompleted etc.
  • #6: addDisposableTo, it is very important, when you subscribe to observables, you need to unsubscribe from it to avoid retain cycles. So we have to invoke DisposeBag which is normally used to keep all things that you want to unsubscribe from in the deinit() process.

Well done, we finished coding activity, and time to run and see cool thing.

Conclusion

Above example is demonstrated the advantage of Rx, the most important thing is to control your brain thinking in Reactive, like staltz shared on Github Gist:

The hardest part of the learning journey is thinking in Reactive. It’s a lot about letting go of old imperative and stateful habits of typical programming, and forcing your brain to work in a different paradigm. I haven’t found any guide on the internet in this aspect, and I think the world deserves a practical tutorial on how to think in Reactive, so that you can get started. Library documentation can light your way after that. I hope this helps you.

However, compare between simple and easy, i guess your choice is simple. Simple for other people who will read your project, maintain it, write CI/CD on it. Let’s help them simplest if you can.

For next blog, i will show you How to make an Observable and Bindings. Maybe making a combination MVVM pattern + RxSwift for example. Now, I thought this blog is enough to you get acquainted Rx by code.

You can download the completed project here. If you’re curious about what else you can do with Rx, check out ReactiveX’s documentation.

I hope you’ve enjoyed this introduction to RxSwift. If you have any questions, comments or feedback please leave it below.

Peace ✌

--

--