In today’s article, we are taking a closer look at what reactive programming in Swift is all about and how we can use this design pattern in iOS apps by leveraging RxSwift. At Instamobile, we are building a ton of cool iOS apps, so we always consider using the most appropriate design patterns to build highly modularized iOS Starter Kits.

rxswift

Do you feel tired and exhausted while searching a ton of RxSwift theories? Do you feel confused by its definitions and have no idea how to use it? This article is for you. In my article, I will not try to explain everything step by step but I am going to give you a high-level overview.

Reactive Programming vs. Imperative Programming

Before diving into the RXSwift details, I want to start with an example. Let’s assume you have two values x1 and x2 and an addition operation. After we perform the addition, the changes from x1 and x2 have no effect on the result. Are you supposed to perform the addition again whenever x1 or x2 changes? No, it’s not only ineffective but also easy to cause a memory leak. This is Imperative Programming.

For Reactive Programming, the result will be updated immediately whenever x1 or x2 changes.

Why should we use RXSwift?

RxSwift is an extremely powerful reactive programming framework for Swift. Here’s a concise list of the benefits RxSwift brings on the table:

  • It makes your application work more smoothly. Especially, it updates the UI in real-time when there is any change in the underlying data. Thanks to this feature, your application will bring a great experience for users.
  • Handle async tasks easier (by removing the need of using various design patterns, such as callbacks, delegates, notifications, KVO, etc, which make your application code complicated and difficult to control and maintain).
  • Improved threads management: switching threads easily.
  • Write less code due to its functions & operators support.
  • Multi-platform: the reactive programming concept is used in many different languages, using the exact same nomenclature, making it extremely easy to reason about this in different environments (e.g. Java, Kotlin, etc).

Alright, after knowing its many benefits, we will find out its components.

2. Basic components of RxSwift

It’s hard to tell what RxSwift really is because it has numerous concepts. Diving deeper could help us understand clearly but it’s also very complicated. In this article, I am going to avoid lengthy step by step explanations in order to save your time. I will introduce this concept in the most understandable and practical way. Let’s first get familiar with the most popular concepts and definitions of RxSwift components:

  • Observable Sequences: They are simply something that will emit the object’s changes to let other classes listen and receive the signal. RxSwift defines them as subscribers. The signal here could be everything: Int, String, Custom type or a gesture.
  • Subjects: Some particular forms of Observable Sequences such as PublishSubject, BehaviourSubject, ReplaySubject, BehaviorRelay (which was Variable). Each type gives us the functions to receive the value change of subscribers when listening or not.
  • DisposeBag: Garbage pickup and removal. It helps automatically deallocate objects from memory (leveraging, of coruse, Automatic Reference Counting mechanism — ARC).
  • Operators: We have a lot of powerful operators supporting us so well such as Map, FlatMap, Filter, DistinctUntilChanged, CombineLatest, etc.
  • Schedulers: The last one is also the most important one. A RxSwift scheduler manages threads before and after the subscriber receives the return value.

Now we’ll move on to the next part.

3. RxSwift Code Example

Before we start, I want to mention a little bit about object life cycles. We’ll have .onNext, .onComplete, .onError. So I will explain what they are, what they are going to do in my examples. And to save your time, I won’t tell you about some things like how to add or install RxSwift, RxCocoa or Podfile. They belong to another article, so feel free to Google those, if you’re just getting started with RxSwift and want to write some starting reactive programming code.

Now, I’ll create a project called IntroductionRxSwift. Then, I’ll install RxSwift pod via Podfile. All codes will live in the viewDidLoad method of the automatically created ViewController class.

Step 1: Create RxSwift Observables:

In viewDidLoad, let’s add these lines of code:

// Create observable with the signal is String
let observable = Observable<String>.create { (observer) -> Disposable in
   observer.onNext(“First signal”)
   observer.onCompleted()
   return Disposables.create()
}

So what do we have here?

  • The signal (which we want to emit) is placed inside of Observable<Type>. In this example, I want to emit a String type, so I put it inside <>, Observable<String> (these are called generics in Swift, which you might already be familiar with if you’re not new to iOS development)
  • The newly created method returns a closure in which we have an `observer` property. On this property, we broadcast the value through the .onNext event.
  • .onCompleted and .onError are responsible for ending the stream. You can not receive any events anymore after calling two methods.

Now that we’ve created Observables, we could listen from them. Simple concept, right?

Step 2. How to create Observers
// Create observers
observable.subscribe(onNext: { (element) in
   print(element)
}).dispose()

We just need to call the `subscribe` method to register to events. Theoretically, we also need to handle .onCompleted and .onError events. But in this article, we just need to care about .onNext.

In the .onNext method, we return a closure with one property. That is the value that we need. We simply print it out, for our simple RxSwift code example.

dispose(): This method is used to clean up and release the observable from memory.

Step 3: Build and run the Xcode project

Now build and run to see what happens. Boom! “First signal” string has been printed out on the Xcode console.

Step 4: Sending a RxSwift Signal after Observer has been completed

The last thing I want to show you is to try sending a signal after calling .onCompleted(). This will be the final code for our quick RxSwift introduction. It’s really the most trivial reactive programming code example: 

// Create observable with the signal is String
let observable = Observable<String>.create { (observer) -> Disposable in
  observer.onNext(“First signal”)
  observer.onCompleted()
  // This signal is sent after calling .onCompleted()
  observer.onNext(“Second signal”)
  return Disposables.create()
}

// Create observers
observable.subscribe(onNext: { (element) in
  print(element)
}).dispose()

After running the code, you’ll notice that “Second signal” is not being printed out to the Xcode console. This is expected – we’ve already completed the stream via observer.onCompleted(), before sending out the second signal. So the stream was already invalid by that time, which resulted in not sending out the second signal.

Hopefully, this was really easy to understand a quick RxSwift Introduction. Try to play around more with the RxSwift and Reactive Programming concepts in Swift playgrounds. I believe you will love it and will use it a lot in the future. It’s a powerful design pattern that has a wide variety of practical applications. Here is the final Github source code. You can refer to it for more details.

Don’t forget to share our article so that more people can learn about RxSwift. Happy Coding!

Categories: iOS Development

Leave a Reply

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