Topics

#162: Reacting with RxSwift ⚗

Topics

We first learned about reactive-style programming in Bite #127, with ReactiveCocoa. (Give that Bite a quick look first if you're new to the topic).

Today we'll check out an alternative solution called RxSwift. It just hit 2.0, so now is a great time to take a look. Let's dive in.

Before we begin it's important to note that there are tons of great libraries available for writing this style of code. We can enjoy the benefits of functional and reactive programming with any of them.

RxSwift is another take on reactive/functional programming. Similar to ReactiveCocoa, RxSwift works with streams of values called Observables. We can subscribe to them, transform them, bind user interface elements to them, and create them.

Additionally, RxSwift ships with RxCocoa, a framework that provides extensions for UIKit that bring it into RxSwift's reactive world.

Let's check out some examples.

Binding a UITextField to a UILabel:

shipNameField.rx_text
  .map { "Launching \($0)..." }
  .bindTo(statusLabel.rx_text)

Creating our own Observable:

Observable<String>.create {
  $0.onNext("Howdy! 🐴")
  $0.onCompleted()

  return NopDisposable.instance
}

Transforming each value change of a search field into an API request, then updating our UI when it completes:

searchBar.rx_text
  .flatMapLatest {
    API.getSearchResults($0)
  }
  .subscribeNext { _ in
    self.tableView.reloadData()
  }

RxSwift can transform how we write code in all the layers of our apps. With tight UIKit integration from RxCocoa, we can now forget about delegates, notifications, KVO, etc and instead use one simple interface to think about how data flows through our app.

Learn more about RxSwift at git.io/rxs