RxSwift: Benefits and Use Cases

Applikey Solutions
HackerNoon.com
6 min readOct 14, 2018

--

Released in 2014, Swift has since become one of the most used programming languages due to its flexibility and relatively easy learning curve. Apart from being compatible with the well-known object-oriented programming (OOP) paradigm, the language also allows writing code in the functional reactive programming (FRP) style (although in its slightly customized, unauthentic form).

In particular, for the FRP purposes, the RXSwift library was created two years after the initial Swift release. It became quite popular in pretty short terms.

Further on, we will talk about this library’s concept, answer the question ‘Why use RXSwift?’, and describe the advantages you get from employing it in your application.

The definitions: what is functional reactive programming?

What is RXSwift? In order to fully understand its purposes, and to answer that question, you should discover what some realted terms mean.

So, what is functional reactive programming (FRP)? Basically, it is the combined employment of reactive programming and functional programming. So figuring out the sense of each method is a must, if you want to define everything properly.

Reactive programming is a special programming paradigm, which automatically changes all variables ‘attached’ to the changes in the performance of an app. For instance, if in imperative programming an assignment statement z = x + y will affect the z value only at the current moment of time, in the case of the reactive programming, the z will automatically transform according to how x and y are customized during the app performance.

It’s like flicking a light switch: the switch and the light bulb are coupling components. In coding terms: suppose that the bulb reacts to the switch and transforms its state accordingly, then it is reactive and the switch is observable, because it only observes the changes in the state of a light bulb.

All in all, reactive programming is about writing code that defines how to react to changes: user input, data coming from a stream, changes in the state of a system, etc.

Functional programming is an opposition to the imperative coding. It allows expressing the system code logics through mathematical relations (i.e. functions) instead of a strict sequence of actions (which is a feature of imperative coding). It allows significantly cutting down the general code volume, making it more susceptible to unit-testing, as well as, decreasing the number of errors that appear in the definition of connections between separate variables.

Thus, functional reactive programming is a principally new solution for the distribution of customizations in the interconnected variables. One of the FRP interpretations is the RxSwift library — the version of Swift with reactive expansions written in the same language. Its purpose is to process asynchronous code executed in the background while the app operates on the user mobile device.

Additionally:

  • it is a tool for composing asynchronous and event-based programs with the help of observable sequences. No need to worry about synchronization, low-level threading, non-blocking I/O, thread-safety, and concurrent data structures. The observer pattern is extended to support data sequences and/or events and the operators are added so that you are able to compose sequences together in a declarative fashion.
  • the ‘observable’ can be employed as a universal, highly-composable pattern. This way, you won’t have to use tons of patterns like completion blocks, target actions, delegations, and many others all at once.

In which cases should RxSwift be used?

First and foremost, you have to realize that the body and soul of RxSwift are observable sequences, i.e., things that perform based on the state changes in the observable sequences.

Most iOS developers note that it is difficult to learn the RXSwift basics. The thing is, though, that the work with asynchronous calls is a complex affair. Due to the difficulty of handling them and the young age of the technology, many not-so-experienced programmers prefer to ignore RxSwift sometimes. It appeared only three years ago and it hasn’t yet had enough time to get the integral volumes of documentation and topical articles. That is exactly why we decided to try to help you understand when and why to use RXSwift, so that you can assess the rationality of spending time learning this technology yourself.

As a matter of fact, if you manage to understand the FRP concept quite well, then you might have already come to the conclusion that RxSwift can significantly simplify your work. Let’s figure out what particular problems this library solves. All in all, use it when:

You are bothered by the frequent necessity to use KVO

KVO (key-value observing) is a technology practiced in Objective-C that allows notifying objects about the specific changes in the state of other objects. However, despite the obvious powerful capabilities of KVO, it is not that popular among programmers. It is usually regarded as a desperate measure and employed only when other solutions are unavailable. The thing is, the technology has quite a significant disadvantage — a serious performance capacities consumption. It is definitely felt when used frequently. In turn, the RXSwift creators solve this issue radically by minimizing the necessity to involve this API at all.

You need to synchronize two requests

In certain cases, the developers must call an API in order to redesign the current UI representation. This happens because not all REST APIs are adapted to the creation of apps for mobile platforms. Providing the synchronization for the calls can be difficult even for an experienced developer. For that, you will have to keep in mind a number of Boolean variables (the value of which may vary when processing user requests), and put effort into creating a class that would organize the interconnectivity of the variables. If you are using RxSwift, you can simply use a zip operator that would combine the two observables and send an answer at the end of processing two API requests.

You don’t want to busy yourself with delegates

As a matter of fact, RxSwift eliminates the strict necessity to use voluminous delegates. Why? UI development is very much related to reacting to various asynchronous tasks. The most trivial way of reacting is using the observer templates. In the case of Swift, those templates are the well-known delegates. The delegates, we believe, significantly helped the developers to solve the issue with asynchronous calls. They were used to transfer methods as arguments to other methods.

However, for that, they required composing a voluminous code which included the creation of a variable, creation, and definition of the protocol, as well as, the installation of the variable. In such a manner, while a developer (or a team of developers) had to work on the one and single interface, the implementation and further usage of delegates required keeping in mind a huge amount of information.

In turn, RxSwift managed to solve this problem completely. This library had introduced the ability to write code in the declarative style without increasing the size of the UIViewController and requiring the objc (usually, they are needed for getting some additional required functions).

You strive to create modular code

Sometimes, developers come across a necessity to use property observers that track any customizations related to the observed and immediately reaction to them. They operate with the didSet (for the execution of code after the property has been customized) and willSet actions (for the execution of code before the property has been customized). On the other hand, code constructions with the employment of the property observers can seem excessively voluminous. Using RxSwift you can cut the total volume of code and make certain parts of it into separate functions.

Summarizing RxSwift’s good sides

Summarizing everything said above in a couple of words, getting started with RxSwift, you may get the following advantages:

  • an ability to write multi-use code;
  • strengths of the declarative coding style;
  • conciseness and readability of code constructions;
  • rational management of app resources;
  • perfect compatibility with the MVVM template;
  • rapid development and wide support;
  • optimal conditions for further development of one’s programmer career (the similar technology also exists both for Java and for JavaScript, so even the basic RxSwift knowledge will help you write cross-platform apps on React-Native, for example).

Reactive programming with Swift: conclusion

As you can see, despite the complexity of mastering theoretical RxSwift, this technology is capable of simplifying the iOS developer’s life. We would like to strongly recommend studying the basics of RXSwift. On the other hand, you can put the responsibility of the technical realization of your iOS project on us! We will provide you with a completely readymade solution not requiring any additional fixes or enhancements (at least for a long period of time — the progress never stands still). Fill out this form in order to discuss all the details of our cooperation and we will contact you very soon!

Originally published at applikeysolutions.com.

--

--