Reactive Programming Patterns for Asynchronous APIs

Real-world scenarios from Stack Overflow

Enrico Piccinin
Better Programming
Published in
9 min readMar 15, 2020

--

Image source: Author

Reactive programming is getting traction and so is the use of ReactiveX libraries. More and more people start using this paradigm and often face similar problems in their learning path. Similar problems call for similar solutions, and this is what patterns are.

An interesting source to understand real-life problems is Stack Overflow. I started looking at the questions around RxJS some time ago, and I’ve noticed some recurring themes and similar situations that people have to deal with.

One popular theme is around asynchronous API calls; in other words, how to deal with HTTP requests in the real world. For instance:

  • How can you call sequentially many asynchronous APIs, each depending on results from the previous ones?
  • How can you turn an array of parameters into an array of asynchronous calls and control their execution?
  • How can you call APIs recursively over time, with a predefined frequency, even if we cannot predict how long each request will take to return?

Let’s see how we can deal with such situations.

Call Sequentially Many Asynchronous APIs to Get the Job Done

Call some REST APIs. For many, this is the first problem with RxJS. REST APIs are asynchronous in nature and can be modeled as a stream of just one value.

An HTTP request as an observable

In real scenarios, we often face the need to issue different API calls to get the job done. Here are some examples of how to deal with these cases.

Merge the results of observables emitting sequentially

Often we need to make some calls sequentially to get what we want. For instance, let’s imagine that we have two APIs, one returning the details of an employee, given their ID, and one returning the details of a department, again given its ID:

  • getEmployee(id: string) : Observable<Employee>

--

--

A man with passion for code and for some strange things that sometimes happen in IT organizations. Views and thoughts here are my own.