RxSwift — Reactive Thinking (Part 1)

Santosh Botre
codeburst
Published in
4 min readDec 7, 2018

--

It has been too long since my last blog. Today, we are gone touch a very exciting moreover a hot topic in a programmer’s life i.e. The Reactive Programming.

It will have a short theory with an in-depth hands-on code example from a regular use case in the development cycle.

We need to change our existing mindset to accomplish the Reactive programming. In short, we need to change our old programming habit/thinking/approach to do Reactive Programming.

I hope you will enjoy reading.

Observable

As the name suggests, it can be observed. It’s like an array as it allows to use map, filter, flat map and reduce operators (or higher order functions) on Observable in the similar way we do it on the Array.

The array is a collection of the data and allows to access any element of the collection any time. However, Observable is an equivalent to a sequence of an event as and when happens.

The observer will get the element as soon as it has been added to the Observable object. It does not allow to go back to the previous event; it’s a past. We can’t change the past.

We can create an Observable for any type of data.

Observable<String>, Observable<Int>, Observable<Bool>struct Person {  let name: String}Observable<[Person]> etc.

Let’s create an Observable,

just -

Transform a single value into the Observable the just() is probably more readable option to choose. just() takes an argument and sends it as next and then it sends completed right after the next.

let elementObservable = Observable.just("Hello World!!!")elementObservable.subscribe {print($0) // will print eventprint($0.element) // will print element from event}Output:-next(Hello World!!!)Optional("Hello World!!!")completednil // completed event don't get any value. $0 is an optional.

of -

Transform a multiple values of same type into the Observable the of() is a right choice. of() takes multiple arguments and send it as sequence of next and then it sends completed right after the last next.

let elementsObservable = Observable.of("Hello World!!!", "Let's Learn", "Put the past behind us!!!")elementsObservable.subscribe {  print($0)}Output:-
next(Hello World!!!)
next(Let's Learn)next(Put the past behind us!!!)completed

from -

Transform an array of elements into the Observable the from() is a right choice. from() takes array as an argument and send it as enumerable sequence of next followed by completed.

let arrayofElementObservable = Observable.from(["Hello World!!!", "Let's Learn"])arrayofElementObservable.subscribe {print($0)}
Output:-
next(Hello World!!!)next(Let's Learn)completed

NOTE: This code is leaking memory, have some patience.

Firstly, understand what is this next() on a console.

On subscription to the observable sequences it can emit zero or more events over their lifetimes.

An Event is emitted with 3 possible states:

  • onNext: When a value or collection of values is added to an observable sequence it will send the next event to its subscribers.
  • OnError: If an Error is encountered, a sequence will emit an error event. This will also terminate the sequence.
  • OnCompleted: If a sequence ends normally it sends a completed event to its subscribers.

On subscription, the observable will return the state on which the just, of or from is applied.

In all the above examples, onCompleted getting called which means it breaks the sequence. Observer will not get the latest element on changing the value of the observable object unless you subscribe it again.

var episodeTitle = "Man vs Wild"// observablelet episodeTitleObservable = Observable.just(episodeTitle)// observerepisodeTitleObservable.subscribe{ print($0)}// Update the value of title.episodeTitle = "World War Z"Output:- next(Man vs Wild)completed 

Observer is unsubscribed/deregister. It will not get the event on change of the value of episodeTitle.

Important: On subscription on the Observable it returns a subscription object(Disposable). Which we can use for unsubscribe from the observable sequence. Which can be used to call the dispose method to cancel the subscription explicitly.

OMG!!! Manual memory management.

  • DisposeBag()

Add subscription in to the Dispose-bag, it will cancel the subscription automatically in deinit of the Disposebag.

// observablelet episodeTitleObservable = Observable.just(episodeTitle)// observerlet disposeBag = DisposeBag()episodeTitleObservable.subscribe{ print($0)}.disposed(by: disposeBag)

You can read about Subject in part 2 and Traits in part 3.

RxSwift — Reactive Thinking (Part 2)

RxSwift — Reactive Thinking (Part 3)

while(true) { clap() }

--

--

Take your time to learn before develop, examine to make it better, and eventually blog your learnings.