Know about the basics of RxSwift in just 10 Minutes

21 Apr 2021

Every developer ought to have known about the basics of RxSwift. Whether it happened at the last developer conference or while reading a fresh blog or article. It is practically incomprehensible not to have known about it, yet the thing precisely is Reactive Programming?

Let’s take a look on the Internet:

In computing, reactive programming is a programming worldview situated around data flows and the propagation of progress. This implies that it ought to be feasible to communicate static or dynamic information streams effortlessly in the programming languages used and that the hidden execution model will consequently propagate changes through the data flow. — Wikipedia

Many people will have no clue about what reactive programming actually is. This is the motivation behind why we will try to make a simple, and easy-to-understand Introduction for this modern approach to software development using the Swift Version of Rx: RxSwift.

1. Observable Sequences

The very first thing that you need to understand is that everything in RxSwift is an observable sequence or something that operates on or subscribes to events released by an observable sequence.

Arrays, Strings or Dictionaries will be turned into observable sequences in RxSwift. You can make an observable sequence of any Object that conforms to the Sequence Protocol from the Swift Standard Library.

Let’s see some observable sequences examples:

You subscribe to observable sequences by calling

subscribe(on:(Event<T>)-> ()).

The passed block will receive all events emitted by that sequence.

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 as seen above. 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

In any case you want to cancel a subscription you can do that by calling dispose on it. You can also add the subscription to a Disposebag which will cancel the subscription for you automatically on deinit of the DisposeBag Instance. Another thing you can do is to subscribe just to a specific Event. For Example, if just want to receive the error events emitted by a sequence, you can use: subscribe(onError:(Error->())).

This Code snippet will cumulative all the things you learned by now:

2. Subjects

A Subject is a special form of an Observable Sequence, you can subscribe and dynamically add elements to it. There are currently 4 different types of Subjects in RxSwift

PublishSubject: If you subscribe to it you will get all the events that will 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 the subscription happened.

ReplaySubject: If you want to replay more than the most recent element to new subscribers 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 just a BehaviourSubject wrapper that feels more natural to a none reactive programmers. It can be used like a normal Variable.

Below there is an example of how the PublishSubject works. If you want to know more about the other subject types, you need to take a look at the accompanying material on GitHub. They basically differ only in the number of past events emitted and received by their subscribers on initial subscription.

Let’s take a look at the PublishSubject.

The first thing we need to do is to create an actual PublishSubject example. This is super simple, we can use the default initializer for that.

You can add new Values to that sequence by using the onNext() function. onCompleted() will complete the sequence and onError(error) will result in emitting an error event. Let’s add some values to our PublishSubject.

If you subscribe to that subject after adding “Hello” and “World” using onNext(), you won’t receive these two values through events. In contrast to a BehaviourSubject, that will receive “World”, which is the most recent event.

Now let’s create a subscription and add some new values to the Subject.

We also create a second subscription and add even more values to it.

Please read the comments to understand what actually is going on.

3. Marble Diagrams

If you work with RxSwift or Rx in general, you should get to know Marble Diagrams. 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.

For Example, let’s take look at an operation that delays your emitted events from an observable sequence by 150 milliseconds. Please ignore the scheduler parameter because we will introduce it later in the blog:

4. Transformations

Sometimes you want to transform, combine or filter the elements produced by an observable sequence before the subscriber receives them. In this article we will introduce you to the basic transformation operators, tell you something about Filters and possibilities to combine sequences. At last your will know how to perform transformations, combinations etc. on different threads.

Let’s get started.

4.1 Map

To transform Elements emitted from an observable Sequence, before they reach their subscribers, you use the map operator. Imagine a transformation that multiplies each value of a sequence with 10 before emitting.

4.2 FlatMap

Imagine an Observable Sequence that consists of objects that are themselves Observables and you want to create a new Sequence from those. This is where FlatMap comes into play. FlatMap merges the emission of these resulting Observables and emitting these merged results as its own sequence.

4.3 Scan

Scan starts with an initial seed value and is used to aggregate values just like reduce in Swift.

4.4 Buffer

The Buffer operator transforms an Observable that emits items into an Observable that emits buffered collections of those items.

5. Filter

If you only want to react on next events based on certain criteria you should use a filter operator.

5.1 Filter

The Basic filter Operation works similar to the swift equivalent. You just define a condition that needs to be passed and if the condition is fulfilled a .next event will be emitted to its subscribers.

5.2 DistinctUntilChanged

If you just want to emit next Events if the value changed from previous ones you need to use distinctUntilChanged.

Other filter operators you should try:




6. Combine

Combining sequences is a common Task. RxSwift provides a lot of operators for you. Here are 3 of them:

6.1 StartWith

If you want an Observable to emit a specific sequence of items before it begins emitting the items normally expected from it, use the startWith operator.

6.2 Merge

You can combine the output of multiple Observables so that they act like a single Observable, by using the Merge operator.

6.3 Zip

You use the Zip method if you want to merge items emitted by different observable sequences to one observable sequence. Zip will operate in strict sequence, so the first two elements emitted by Zip will be the first element of the first sequence and the first element of the second sequence combined. Keep also in Mind that Zip will only emit as many items as the number of items emitted of the source Observables that emits the fewest items.

Other combination filters you should try:

  • Concat
  • CombineLatest
  • SwitchLatests

7. Side Effects

If you want to register callbacks that will be executed when certain events take place on an Observable Sequence you need to use the doOn Operator. It will not modify the emitted elements but rather just pass them through.

You can use …

  • do(onNext:) – if you want to do something just if a next event happened
  • do(onError:) – if errors will be emitted and
  • do(onCompleted:) – if the sequence finished successfully.

8. Schedulers

A scheduler can be serial or concurrent similar to GCD or OperationQueue. There are 5 Types of Schedulers in RxSwift:

  • MainScheduler
  • CurrentThreadScheduler
  • SerialDispatchQueueScheduler
  • ConcurrentDispatchQueueScheduler
  • OperationQueueScheduler

Here is a code snippet that shows you how to observe something concurrently on a background queue und subscribe on the main-queue.

Winding Up

Naxtre is a result-driven and innovative RxSwift app development company, which aims to render quality mobile app development services with expeditious project delivery. Our highly skilled app developers have decades of experience in developing mobile apps using RxSwift for iPhone, iPad and wearables. For RxSwift App development services REACH US today!