fbpx

I skipped ahead in my last few technical posts where I talked about reactive programming implementation via RxJS. To fully understand the effectiveness of something, it’s always good to start from the beginning. Therefore, in this post I will take a few steps back and explore reactive programming. I will talk about the pros and cons of reactive programming followed by a few simple code samples.

Background

I started working with reactive programming sometime in 2018 when I was building Ionic apps. Of course in 2019 and 2020 my usage increased quite a bit when I was building apps for other startups. In fact, that lead to some of my earlier posts on problem solving in reactive programming. Posts like,

Those posts are informative but they are focused on implementation details. This is great for solving problems. However what is reactive programming? What exactly does it mean to be reactive? I mean, how does a system go about being reactive? Let’s me try to answer some of those questions, starting with,

What is reactive programming?

The formal definition of this would be something like, “it’s (reactive) a programming paradigm that deals with asynchronous data streams and the propagation of change” Does it makes sense? To me, not as much at first glance. So let me try to break it down further and see if I can explain it better. Let’s start by understanding what asynchronous data streams are.

Why do we need asynchronous data streams?

These days making software isn’t hard, there are million of apps out there and pretty much anyone with a computer can make an app. However an app can differentiate itself from others is by giving users better UX or a smooth uninterrupted user experience.

Example

For an app that shows the weather info, the user can tap a button to fetch the latest local weather info. Once tapped the app can fetch info from a server while not blocking the user from using other features while the data is retrieved in background. To do so, the app will trigger an asynchronous operation where it will send a request to a server and be notified via a callback when it gets a response. While the process of fetching the latest weather info is in progress, the app is responsive so the user can do other things. e.g. add another city besides the current location.

This is what I meant by smooth user experience. Now let me try to explain propagation of change the best I can.

Propagation of change

This one is quite simple, really. For the purpose of this, let’s say we have a parent variable which we initialise by assigning values from its child (or children) variable (s). Now, if any any point during the program’s execution, if the child (ren) variable (s) change its values, the parent value will be updated. Hence, the change in the child variable is propagated all the way to the top, it’s parent. Therefore we don’t need to worry about updating the parent variable based on the latest value of its child.

Example

In our weather example above, when we fetch the latest information for the local weather via a reactive approach. We update our as UI as soon as we receive the latest data via a callback function. If this is done using Javascript Promises, the callback function would be a one off. However if done using a reactive approach by using an Observable after the initial data fetch, we have opened a channel for receiving data. This means that every time the asynchronous operation fetches data for the latest weather, our weather info variable is automatically updated to reflect that. Hmmm ok, let’s summarise this in bullet points

  • we want to show the user the latest local weather data
  • we create a local variable w to store weather info
  • we initialise w as an asynchronous fetch operation done reactively
  • w is assigned the latest info when the fetch operation completes
  • by now open a channel to get the latest data (e.g. observable)
  • every time new weather info is obtained, the change is propagated i.e. w is initialised with the latest value

Pros & cons of reactive programming

This almost sounds perfect, doesn’t it? Maybe or maybe not! Let’s look at a few pros & cons of reactive programming.

Pros (Advantages)

Applying logic to everything we talked about earlier, we can safely assume reactive programming gives us,

Better performance i.e. better use of CPU as opposed to single threaded execution e.g. the Javascript event loop.

Improved UX – we talked about this earlier. If your app’s IO operations are done asynchronously, that means very little or few blocking operations. That means the user gets smooth responsive UI leading to a great user experience.

Cleaner code – I mean, you saw this one coming didn’t you? If we keep making and resolving promises, before long we find ourselves in callback hell. Know what I mean, right? Actually, let’s have a look at what I mean

let promiseA = new Promise((resolve, reject) => {});
let promiseB = new Promise((resolve, reject) => {});
let promiseC = new Promise((resolve, reject) => {});

promiseA.then(result1 => {
  // do something with result 1
  promiseB.then(result2 => {
    // do something with result 2
    promiseC.then(result3 => {
       //do something with result 1, 2 and 3
    })
  })
})

See the code above? Firstly, the code above is “callback hell” secondly it’s a one-off. What if one of the promises above yields another value during the program’s life cycle, after it was first resolved? How do we get the value? we have already resolved the promise.

Remember, we talked about how every time a new value is generated (or emitted), the change is propagated all the way to the top. This means if the problem above was solved using Observables, no need to worry about resolving a promise to get the latest value. Every time the observable emits a new value, the change would be propagated all the way to the top. Ok to understand it, let’s look at a,

Scenario

Say, we have a shopping list, to which we add items at random intervals and let’s see how we implement that reactive (ly) e.g. using RxJS.

let shoppingList = new Observable(subscriber => {
  setTimeout(() => {
    subscriber.next("Milk");
  }, 200);
  setTimeout(() => {
    subscriber.next("Cheese");
  }, 200);
  setTimeout(() => {
    subscriber.next("Biscuits");
  }, 200);
  setTimeout(() => {
    subscriber.complete();
  }, 500);
});

For our front-end to get the values emitted by the shoppingList Observable, it would need to subscribe to it.

shoppingList.subscribe(item => {
  console.log(`Adding item: ${item}`);
});

Cons or when to avoid it?

For starters, it’s not the easiest to get into as it has a steep learning curve. I remember, how I struggled to get my head around Observables, streams and all. It took a little reading, a bit of back and forth until I was confident enough to write reactive code.

Since everything is a stream and there’s the propagation of change, it means high consumption of memory. Reactive programming is all about streams over time and storing streams consumes memory. So you need to factor in that overhead.

As a software engineer, it can be tempting to use the new “cool” tech that we just discovered to solve problems. As tempting as it is, one must be mindful of not forcing a solution onto a problem. What do I mean? For example, applying reactive programming to an app where there’s no ‘live’ data adds little value at the cost of increasing complexity.

Conclusion

What’s a modern software system, compared to those in the 90s? Well, it’s clean, fast, responsive and it cares a great deal about the user e.g. UX. Back in the day, building software was about building features, now making software isn’t hard so the software’s UX is it’s selling point. Hence engineers are always working towards making the user journey as smooth as possible. Hence, while reactive programming isn’t a completely new concept, a recent surge in popularity is owing to how it helps with UX. While it can be a bit intimidating at first, once you get past the initial learning curve, it’s not as challenging as it first seems. An over simplification would be to say it’s about dynamically updating variables. Dig deeper and you will realise that it’s propagating of change with respect to asynchronous data streams.

I like reactive programming I think it’s a great way to build systems. I will continue to write more on reactive programming and explore RxJS and it’s operators in more detail.

In this post we explored the pros & cons of reactive programming along with some code samples. I feel this should be enough to get anyone started on reactive programming. If something is not clear, please leave a comment and let me know how I can improve or better explain this post.

Like the blog? Subscribe for updates

As usual, if you find any of my posts useful support me by  buying or even trying one of my apps on the App Store. 

https://mydaytodo.com/apps/

Also, if you can leave a review on the App Store or Google Play Store, that would help too.


0 Comments

Leave a Reply

Avatar placeholder

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