diskodev

DESIGN & DEVELOPMENT AGENCY

Part 1 - Introduction to RxSwift

This is part of a series on Reactive Programming in RxSwift.

RxSwift is a reactive extension for Swift. Reactive extensions are a combination of the best ideas from the Observer pattern, Iterator pattern and Functional Programming. Reactive extensions are available for Java, Scala, C#, C++, JavaScript, Python, Clojure, Kotlin among others. The programming model of RxSwift is similar to reactive extensions present for other languages and is more than a set of APIs. It is a new way of building applications that are responsive, resilient, elastic and message driven.

What is Reactive Programming?

Reactive programming is programming with asynchronous streams or observable sequences (or simply sequences). It involves streams, its transformations and the bindings that goes with it. State changes / new data are passed on as streams which you can observe and work on. Anything can be a stream: variables, events, properties, requests / responses, etc. You can listen to any number of streams and react.

It is not useful to just observe streams. You are provided tools to transform any of those streams. You can chain any of those transformations and create a new stream altogether. And, you can bind streams to properties, UI elements, etc. This makes it easier to write and structure your asynchronous program.

Consider the following piece of code:  

var health = 100.00
var playerCritical = health <= healthCutoffValue
if playerCritical { // Do Something } else { // Do Another Thing }

Here, the variable playerCritical is dependent on health being less than a cutoff value. We check if the player is critical and do some work based on it. But what happens when the player becomes critical sometime later in the game? Maybe, you need to execute a piece of code when the player is critical. This is where Reactive Programming comes in. You can subscribe to playerCritical and when the value changes, you are passed the current stream (or value) and execute your code when it reaches a cutoff level. See how simple your program's data flow becomes. And as specified earlier, anything can be a stream.

This is just a simple example, but we will see much more in the later series about the full power of Rx and in specific to iOS / macOS development.

Benefits of Reactive Programming

So, what are the benefits of Rx? why should you be using it in your projects?

  • Rx enables you to use immutable definitions and pure functions to process snapshots of streams in a reliable composable way. You can easily compose your program into clean input/output functions with its own handlers
  • Rx helps building asynchronous programs to react to new data/events. It lets you write highly performant code that handles huge number of streams/events. Using the tools provided you can write highly interactive applications very easily
  • It is very easy to reason about what your asynchronous program does and how the handlers works for the asynchronous streams. The dataflow is clear and you can easily understand how a block of code works
  • You can easily manage state across your app. Rx provides tools to share state across various asynchronous streams - if you want to
  • The code you write with Rx is very declarative since definitions are immutable and only the streams change over time thus reducing side effects
  • Rx easily lets you bind to UI elements, always representing the latest app state with less work
  • Rx tools provide tools to make resource management simple and easy
  • Reactive extensions exhibits consistent behavior across all platforms. They have common patterns, similar operators and along with libraies for major languages, they aid in cross-platform development. A developer familiar with the Rx library can easily work on code bases with the extensions irrespective of the language or platform
  • Rx has a huge community. Help is always around if you are stuck at a problem. Reactive extensions are being developed for all environments imaginable and the community is very forward thinking. Extensions also specifically target a particular platform. e.g, ReactiveCocoa wraps various aspects of cocoa frameworks with Rx primitives to aid cocoa development

RxSwift Installation

Using Cocoapods, your Podfile will look similiar to this (For testing, you will use a blocking version of RxSwift), before running $pod install:

use_frameworks!

target 'YOUR_TARGET_NAME' do
    pod 'RxSwift',    '~> 3.0'
    pod 'RxCocoa',    '~> 3.0'
end

target 'YOUR_TESTING_TARGET' do
    pod 'RxBlocking', '~> 3.0'
    pod 'RxTest',     '~> 3.0'
end

Using Carthage, your Cartfile will look like the following before running $carthage update

github "ReactiveX/RxSwift" ~> 3.0

Using the Swift Package Manager, your Package.swift will look like the following before running $swift build:

import PackageDescription

let package = Package(
    name: "RxTestProject",
    targets: [],
    dependencies: [
        .Package(url: "https://github.com/ReactiveX/RxSwift.git", majorVersion: 3)
    ]
)

If you want to use it as a git submodule, installation instructions can be found here.

You can run RxSwift in the Playground too. Instructions to run it on the Playgrounds can be found here.

Other Links

You can read more about Rx and the various operators under it here. You can also check the tutorials section for other language Rx implementations. Swift projects using Rx can be browsed here.

What Next?

We will be looking into the core concepts of RxSwift, the operators available, error handling, writing concurrent code and also testing your Rx code. We shall also look at the best architecture for your reactive applications together with platform specific features with a lot of code samples.

That's it for now.

You can view my projects on github.

You can follow me on twitter.