In this tutorial, we’ll be discussing the basics of RxSwift in our XCode Project. Before we get into the nitty-gritty details, lets setup RxSwift.

Setting Up RxSwift

RxSwift is an iOS Library. Before we discuss what’s more in store lets create a new XCode Project.
Goto the folder path from your terminal and do a pod init.

A new PodFile gets created in your XCode Project.
Open the PodFile using vim Podfile and add the following statement below use_frameworks!.


Now in your terminal, do a pod install.

Congrats! You can now import RxSwift in your Project.
Now close your project and open it using the new xcworkspace file created.

RxSwift Basics

RxSwift is a reactive programming used for iOS Development. It follows the paradigm wherein it responds to changes.

RxSwift consists of two main components – Observable and Observer.

Observable emits items.
An observer which is Subscribed to the Observable watches those items.

Using Operators we can transform the items.

Now that we’ve successfully installed the RxSwift pod, lets import RxSwift in our ViewController.swift file.


Observables in RxSwift can be defined in the following ways:

We can subscribe to an observable sequences by calling
subscribe(on:(Event)-> ()) over it.


The events emitted in the subscribe method are sequences.
An event is an enum type which can have the following three possible values:

  • .next(value: T) — Each value emitted is returned in the value here.
  • .error(error: Error) — This gets called when there is an error.
  • .completed — This gets called after all the items are emitted

The output of the above code in the console is:

RxSwift simplifies Multi threading.

To cancel a subscription we can call dispose on the subscription instance.
Another way to dispose subscriptions is to add them to a DisposeBag.

When deinit for the DisposableBag instance is called, the subscription is automatically canceled.


We can transform the emitted items in RxSwift using Operators.

Operators that are commonly used are:

Using map operator:

Output is :

The filter operator is used to filter the emitted items such that items that pass the condition would be shown in the final emission.


FlatMap is used to create a new sequence from other sequences.

The output is:

As you can see a FlatMap flattens the arrays.


Subjects are Observables only, but with special properties.

Subjects can be divided into the following types:

  • PublishSubject: This emits all items when subscribed.
  • BehaviourSubject: The subscriber when subscribed to such observables, would get only the last recently emitted item.
  • ReplaySubject: All the items would be replayed. You can specify how items you want to get replayed.

Let’s look at an example of BehaviourSubject:

The above code prints [1] since it was the last emitted item.

And that brings an end to this tutorial.

By admin

Leave a Reply