Filed Under: Swift

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!.


pod 'RxSwift'
pod 'RxCocoa'

rxswift podfile

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 project xcworkspace

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

Observables in RxSwift can be defined in the following ways:


let justObservable = Observable.just("Hello RxSwift")
let arrayObservable = Observable.from([1,2,3])
let dictionaryObservable = Observable.from([1:"Hello",2:"Rx"])

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

Subscribing


let dictSubscribe = dictionaryObservable.subscribe{event in print(event)}
        
let arraySubscription = arrayObservable.subscribe { event in
            switch event {
            case .next(let value):
                print(value)
            case .error(let error):
                print(error)
            case .completed:
                print("completed")
            }
        }

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 output 1

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.


let bag = DisposeBag()
bag.addDisposableTo(dictSubscribe)

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

Operator

We can transform the emitted items in RxSwift using Operators.

Operators that are commonly used are:

  • map
  • filter

Using map operator:


Observable<Int>.of(1,2,3,4,5,6,7).map { value in
            return value * value
            }.subscribe(onNext:{
                print($0)
            })

Output is :

rxswift output 2

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


Observable<Int>.of(1,2,3,4,5,6,7).filter{$0>8}.subscribe(onNext:{
                print($0)
        })


FlatMap

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


let observable1  = Observable<Int>.of(1,2)
let observable2  = Observable<Int>.of(3,4)
        let observableOfObservables = Observable.of(observable1,observable2)
        observableOfObservables.subscribe(onNext:{
            print($0)
        })
        observableOfObservables.flatMap{ return $0 }.subscribe(onNext:{
            print($0)
        })

The output is:

rxswift output 3

As you can see a FlatMap flattens the arrays.

Subjects

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:


let subject = BehaviorSubject(value: [10, 20])
        
        subject.onNext([1])
        
        subject.asObserver().subscribe(onNext: { value in
            print(value)
        })

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

And that brings an end to this tutorial.

Comments

  1. sheetal says:

    Thanks for the tutorial!!!!

  2. Veera says:

    Thank you, simply explained it, please request to give some more topics in RxSwift

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages