Some time ago, we wrote a blog post on what Reactive programming is. As a technique, reactive programming has become so popular that more than 40 languages, including Java, have evolved to support reactive programming techniques. Reactive programming powers the codebases of some of the world’s largest online platforms such as Netflix, AirBnB, and Crunchbase. So clearly, it’s a technique worth familiarising yourself with.

One of the key principles underpinning Reactive programming is the use of asynchronous data streams. But what is an asynchronous data stream? Simply put, an asynchronous data stream is a stream of data where values are emitted, one after another, with a delay between them. The word asynchronous means that the data emitted can appear anywhere in time, after one second or even after two minutes, for example. 

With Reactive programming, data streams will become the spine of your application. Events, messages, calls, and even failures will be conveyed by a data stream. In a reactive programming environment, these streams will be observed and reacted to, when a value is emitted.

What are the key benefits of using Reactive techniques in your codebase?

  • Functional
    Reactive programming will allow you to avoid intricate stateful programs. Instead, you will be able to make use of clean input/output functions over observable streams
  • Asynchronous
    Traditional try/catch methods cannot handle errors in asynchronous computations, but ReactiveX is equipped with better mechanisms to handle errors.
  • Less is more
    Reactive programming provides developers with operators and transformation elements, which can be used to convert boilerplate into fewer lines of code.
  • Concurrency
    Reactive programming also provides new schedules and observers to handle threading and queues.

Getting Started

RxSwift is one of the best ways to deploy reactive code in your application, especially if you develop for iOS. Essentially, it is Swift’s own version of ReactiveX (or Rx). The more technically inclined amongst us would think of RxSwift as a library to compose asynchronous and event-based code using observable sequences and functional style operators, which allows for parameterized execution through schedulers.

RxSwift can be installed through CocoaPods just like any other pod library. A typical Podfile would look something like this:

# Podfile
use_frameworks!
target 'YOUR_TARGET_NAME' do
    pod 'RxSwift',    '~> 4.0'
    pod 'RxCocoa',    '~> 4.0'
End

Next, run podfile to install the RxSwift library to your project.

$ pod install

Understanding the RxSwift Landscape

There are a few key elements in the RxSwift universe which you must keep in mind at all times.

Observable Sequences, Observables and Observers

Everything in RxSwift is an observable sequence, or something that operates on or subscribes to events emitted by an observable sequence. Observable sequences which will emit data continuously for one or more instances are simply called ‘Observables’.

Observers on the other hand, can subscribe to these observable sequences to receive asynchronous notifications as new data is gathered to perform operations.
Observable sequences can emit zero or more events over their lifetimes.

In RxSwift an Event is just an Enumeration Type with 3 possible states:

  • .next(value: T)
    When a value or collection of values is added to an observable sequence it will send the next event to its subscribers. The associated value will contain the actual value from the sequence.
  • .error(error: Error)
    If an Error is encountered, a sequence will emit an error event. This will also terminate the sequence.
  • .completed
    If a sequence ends normally it sends a completed event to its subscribers.

Subjects

Subjects are a special form of observable sequences, to which you can subscribe and dynamically add elements. Currently, RxSwift has four different kinds of subjects.

  • PublishSubject:
    If subscribed to, you will be notified of all the events that happen after you subscribed.
  • BehaviourSubject:
    A behavior subject will give any subscriber the most recent element and everything that is emitted by that sequence after subscription.
  • ReplaySubject:
    If you want to replay more than the most recent element to new subscriber on the initial subscription, you need to use a ReplaySubject. With a ReplaySubject, you can define how many recent items you want to emit to new subscribers.
  • Variable:
    A variable is nothing but a BehaviourSubject wrapper which feels more natural to non-reactive programmers. It can be used just like a normal variable.

Operators

Operators are used to filter, transform or combine data sequences before sending them to subscribers. RxSwift provides what is known as a ‘Marble Diagram’ to help select the operators you need. A Marble Diagram visualizes the transformation of an observable sequence. It consists of the input stream on top, the output stream at the bottom and the actual transformation function in the middle.

Schedulers

Schedulers are used to create thread safe operations. Generally, operators will work on the same thread where the subscription was created. With the use of a scheduler, operators can be forced to work on a specific queue.

RxSwift has five types of schedulers:

  • MainScheduler
    This scheduler abstracts work that needs to be performed on MainThread. In case schedule methods are called from the main thread, it will perform the action immediately without scheduling. This scheduler is usually used to perform UI-related work.
  • CurrentThreadScheduler
    This scheduler schedules units of work on the current thread. This is the default scheduler for operators which generate elements.
  • SerialDispatchQueueScheduler —
    This scheduler abstracts work that needs to be performed on a specific dispatch_queue_t. It will make sure that even if a concurrent dispatch queue is passed, it is transformed into a serial dispatch instead. Serial schedulers enable certain optimizations for observeOn.The main scheduler is an instance of the SerialDispatchQueueScheduler at work.
  • ConcurrentDispatchQueueScheduler —
    This scheduler abstracts work that needs to be performed on a specific dispatch_queue_t. You can also pass a serial dispatch queue, and it should not cause any problems. This scheduler can be used when some work needs to be performed in the background of the application.
  • OperationQueueScheduler —
    This scheduler abstracts work that needs to be performed on a specific NSOperationQueue. This scheduler is suitable for instances where there is some bigger chunk of work that needs to be performed in the background and you want to fine tune concurrent processing using the maxConcurrentOperationCount. function.

And that’s about it. You have now successfully learned the basics of RxSwift. Feel free to give RxSwift a try yourself by clicking on https://github.com/ameera/LoginWithRxSwift 

Happy coding!

References:

  1. Ameera Damsika: Tech Talk on RxSwift
    https://www.facebook.com/calcey/videos/vb.199985621561/2478458815600885/?type=2&theater
  2. https://medium.com/@duydtdev/concepts-about-rxswift-and-how-to-install-rxswift-library-to-project-5a1c3484ca6e
  3. https://medium.com/ios-os-x-development/learn-and-master-%EF%B8%8F-the-basics-of-rxswift-in-10-minutes-818ea6e0a05b