Welcome to RxSwift: Beginner

Its Ratan
8 min readApr 7, 2021

--

1. Introduction to Reactive Programming

In mobile application development, user experience is one of the major requirement to achieve where our application is smooth, interactive & avoid lagging in data updating, Reactive Paradigm is one approach to attain these features.

Reactive programming is an approach to writing software that embraces asynchronous I/O. Asynchronous I/O is a small idea that portends big changes for software. The idea is simple: alleviate inefficient resource utilisation by reclaiming resources that would otherwise be idle as they waited for I/O activity. Asynchronous I/O inverts the normal design of I/O processing: the clients are notified of new data instead of asking for it; this frees the client to do other things while waiting for new notifications. Let’s look at an example that compares and contrasts asynchronous I/O to synchronous I/O.

2. Why you would love to use it?

We want to deliver a fabulous experience to user without freezing the main thread. To make main thread free, we need provide a mechanism to transfer heavy task & complex calculations, this mechanism is achieved with help of implementing asynchronous task execution.

Reactive programming is an asynchronous programming paradigm concern with data streams and propagation of change over time.

In simple words, In Rx programming data flows emitted by one component and the underlying structure provided by the Rx libraries will propagate those changes to another component those are registered to receive those data changes. Long story short: Rx is made up of three key points.

RX = OBSERVABLE + OBSERVER + SCHEDULERS

3. What is RxSwift?

RxSwift is a library for composing asynchronous and event-based code by using observable sequences and functional style operators, allowing for parameterised execution via schedulers.

RxSwift is a Reactive Extensions version written in Swift. Through RxSwift It just simplifies (sic!) your work. Instead of notifications, which are hard to test, we can use signals. Instead of delegates, which take a lot of place in the code, we can write blocks and remove multiple switches/ifs.

We also have KVO, IBActions, input filters, MVVM and many, many more which are handled smoothly by RxSwift. Remember, it’s not always the best way to solve a problem, but you have to know when to use it to its full potential.

4. Some Definitions

Your smartphone is observable. It emits signals like Facebook notifications, messages, Snapchat notifications and so on. You are naturally subscribed to it, so you get every notification in your home screen. You can now decide what to do with that signal. You are an observer.

SubjectObservable and Observer at once. Basically it can observe and be observed.

BehaviorSubject — When you subscribe to it, you will get the latest value emitted by the Subject, and then the values emitted after the subscription.
PublishSubject — When you subscribe to it, you will only get the values that were emitted after the subscription.
ReplaySubject — When you subscribe to it, you will get the values that were emitted after the subscription, but also values that were emitted before the subscription. How many old values will you get? It depends on the buffer size of ReplaySubject you subscribe to. You specify it in init of the Subject.

RxSwift comprises five separate components depending on each other in the following way:

  • RxSwift: The core of RxSwift, providing the Rx standard as (mostly) defined by ReactiveX. It has no other dependencies.
  • RxCocoa: RxCocoa is RxSwift’s companion library holding all classes that specifically aid development for UIKit and Cocoa.
    Besides featuring some advanced classes, RxCocoa adds reactive extensions to many UI components so that you can subscribe for various UI events out of the box.
    Provides Cocoa-specific capabilities for general iOS/macOS/watchOS & tvOS app development, such as Shared Sequences, Traits, and much more. It depends on both RxSwift and RxRelay.
    For example, it’s very easy to use RxCocoa to subscribe to the state changes of a UISwitch, like so:
toggleSwitch.rx.isOn  
.subscribe(onNext: { enabled in
print( enabled ? "it's ON" : "it's OFF" ) })
  • RxRelay: Provides PublishRelay, BehaviorRelay and ReplayRelay, three simple wrappers around Subjects. It depends on RxSwift.
  • RxTest and RxBlocking: Provides testing capabilities for Rx-based systems. It depends on RxSwift.

5. Detailing of Key Terms

Observables:
The Observable<T> class provides the foundation of Rx code: the ability to asynchronously produce a sequence of events that can “carry” an immutable snapshot of data T. In the simplest words, it allows classes to subscribe for values emitted by another class over time.

The Observable<T> class allows one or more observers to react to any events in real time and update the app UI, or otherwise process and utilize new and incoming data. The ObservableType protocol (to which the Observable<T> conforms) is extremely simple.

An Observable can emit (and observers can receive) only three types of events:

• A next event: An event which “carries” the latest (or “next”) data value. This is the way observers “receive” values.

• A completed event: This event terminates the event sequence with success. It means the Observable completed its life-cycle successfully and won’t emit any other events.

• An error event: The Observable terminates with an error and it will not emit other events.

When talking about asynchronous events emitted over time, you can visualize an observable sequence of integers on a timeline, like so:

This simple contract of three possible events an Observable can emit is anything and everything in Rx. Because it is so universal, you can use it to create even the most complex application logic.

Because the observable contract does not make any assumptions about the nature of the Observable or the Observer, using event sequences is the ultimate decoupling practice. You don’t ever need to use delegate protocols, or inject closures to allow your classes to talk to each other.

This workflow accurately describes the lifecycle of a typical observable. Take a look at the related code below:

API.download(file: "http://www...")   
.subscribe(onNext: { data in
... append data to temporary file
},
onError: { error in
... display error to user
},
onCompleted: {
... use downloaded file
})

API.download(file:) returns an Observable<Data> instance, which emits Data values as chunks of data come over the network.

You subscribe for next events by providing the onNext closure. In the downloading example, you append the data to a temporary file stored on disk.

You subscribe for an error by providing the onError closure. In the closure you can display the error.localizedDescription in an alert box or do something else. Finally, to handle a completed event,

you provide the onCompleted closure, where you can push a new view controller to display the downloaded file or anything else your app logic dictates.

Operators:
ObservableType and the implementation of Observable class include plenty of methods that abstract discrete pieces of asynchronous work, which can be composed together to implement more complex logic.

Because they are highly decoupled and composable, these methods are most often referred to as operators. Since these operators mostly take in asynchronous input and only produce output without causing side effects, they can easily fit together, much like puzzle pieces, and work to build a bigger picture.

For example, take the mathematical expression (5 + 6) * 10–2.

In a clear, deterministic way, you can apply the operators *, ( ), + and — in their predefined order to the pieces of data that are their input, take their output and keep processing the expression until it’s resolved.

Scheduler:
Schedulers are the Rx equivalent of dispatch queues — just on steroids and much easier to use. RxSwift comes with a number of predefined schedulers, which cover 99% of use cases and hopefully means you will never have to go about creating your own scheduler.
In fact, most of the examples in the first half of this book are quite simple and generally deal with observing data and updating the UI, so you won’t look into schedulers at all until you’ve covered the basics.
That being said, schedulers are very powerful.

For example, you can specify that you’d like to observe for next events on SerialDispatchQueueScheduler, which uses Grand Central Dispatch to serialise running your code on a given queue.

Dispose Bag:
It is an additional tool RxSwift provides to help deal with ARC and memory management. Deallocating a parent object results in the disposal of Observer objects in the DisposeBag.

When deinit() is called on the object that holds the DisposeBag, each disposable Observer is automatically unsubscribed from what it was observing. This allows ARC to take back memory as it normally would.

Without a DisposeBag, you’d get one of two results. Either the Observer would create a retain cycle, hanging on to what it’s observing indefinitely, or it could be deallocated, causing a crash.

let aDisposableBag = DisposeBag()
let thisIsAnObservableStream = Observable.from([1, 2, 3, 4, 5, 6])
let subscription = thisIsAnObservableStream.subscribe(onNext: { print("Next value: \($0)")
},
onError: {
print("Error: \($0)")
},
onCompleted: {
print("Completed")
})
// add the subscription to the disposable bag
// when the bag is collected, the subscription is disposed
subscription.disposed(by: aDisposableBag)
// if you do not use a disposable bag, do not forget this!
// subscription.dispose()

Transformations:
Transformations allow you to create new observable streams by combining, filtering, or transforming the events emitted by other observable streams. The available transformations include the following:

· map: This transforms each event in a stream into another value before any observer can observe that value. For example, you could map the text property of a UISearchBar into an URL to be used to query some remote service.

· flatMap: This transforms each event into another Observable. For example, you could map the text property of a UISearchBar into the result of an asynchronous query.

· scan: This is similar to the reduce Swift operator on sequences. It will accumulate each new event into a partial result based on all previously emitted events and emit that result.

· filter: This enables filtering of emitted events based on a condition to be verified.

· merge: This merges two streams of events by preserving their ordering.

· zip: This combines two streams of events by creating a new stream whose events are tuples made by the successive events from the two original streams.

6. Installation of RxSwift

RxSwift is distributed under the MIT license, which in short allows you to include the library in free or commercial software, on an as-is basis. As with all other MITlicensed software, the copyright notice should be included in all apps you distribute.

Installation in iOS & Xcode project:

Requirements:
Xcode 12.x
Swift 5.x
for Xcode 11 & below follow following details: https://github.com/ReactiveX/RxSwift/releases/tag/5.1.1

RxSwift through Cocoa Pods:

#Podfileuse_frameworks!
target 'YOUR_TARGET_NAME' do
pod 'RxSwift', '6.0.0-rc.2'
pod 'RxCocoa', '6.0.0-rc.2'
end
# RxTest and RxBlocking make the most sense in the context of unit/integration tests
target 'YOUR_TESTING_TARGET' do
pod 'RxBlocking', '6.0.0-rc.2'
pod 'RxTest', '6.0.0-rc.2'
end

Replace YOUR_TARGET_NAME and then, in the Podfile directory, type:

$ pod install

For other ways of dependency management kindly go through following link:
https://cocoapods.org/pods/RxSwift

7. How to Use RxSwift

For using RxSwift inside an Xcode Project after installation we need to import it into source code in following way:

import RxSwift
import RxCocoa

8. Further Learning

We gone through basic detailing & overview of the Reactive Programming with RxSwift. For further learning we need to implement some of features with help of RxSwift. You can go through following links & try it by yourself:

http://www.thedroidsonroids.com/blog/ios/rxswift-by-examples-1-the-basics
https://www.thedroidsonroids.com/blog/rxswift-examples-3-networking
https://www.thedroidsonroids.com/blog/rxswift-examples-4-multithreading
https://www.thedroidsonroids.com/blog/rxswift-by-examples-2-observable-and-the-bind

9. Conclusion

There are a lot of stuff that need to be added to understand the whole concept behind reactive approach of problem solving. This document provides a basic understanding & tell about how to start. There are books on RxSwift implementation & reactive programming that need to follow to be expert in this segment. Also practice makes the things clearer & practical.

--

--

Its Ratan
Its Ratan

Written by Its Ratan

I am iOS developer interested in latest trends in technology. I am beginner at this platform so let me know so that I can improve & make it better.