Escaping Pipeline Hell

John Freeman
Jan 9, 2019 · 4 min read

Previously, I stepped through the evolution of asynchronous programming in JavaScript, from callback hell, through promises, and leaving off where most coverage stops, at async functions (built on top of the underlying technology of generators). Given that history, I want to talk about the state of asynchronous programming with observables in JavaScript.

Observables

For my novice readers, you can think of observables as promises that can resolve more than once, effectively yielding multiple values. In the same way you attach success and failure callbacks to promises, you subscribe to an observable with callbacks for three types of events: zero, one, or more value events; zero or one error events; and zero or one completion events. The error and completion events are terminal events: there will be at most one of them, never both, and once that event arrives, no more events of any kind will be seen. These callbacks are generally called the next, error, and complete callbacks, respectively. Taken together, they form an observer.

Observables can be constructed from many diverse kinds of sources, including arrays, generators, and promises (which are just observables that yield at most one value). In a famous example from Erik Meijer’s excellent introduction to observables, entitled Your Mouse Is a Database, he arrives at a succinct implementation of an autocomplete (or “type-ahead”) text box using observables. It has been replicated many times over, and in the latest JavaScript, it might look like this:

One more advantage that observables have over promises is that a subscription can be canceled, which lets an observable know that it can stop doing work. This is very useful for canceling AJAX requests whose responses are no longer needed, as in the autocomplete example when the user has edited the text box before the last autocomplete results have returned. There was a proposal for cancelable promises, but it was withdrawn. Without investigating too deeply, I got the impression that it was shouted down in favor of the existing and more general abstraction of observables.

As you can see in the example above, however, observables suffer from the same “chain of callbacks” style that promises had before generators arrived. I’m calling this pipeline hell in the spirit of callback hell. We’re missing the observable equivalent of async functions.

RxJS

RxJS is the most popular implementation of observables for JavaScript, to my knowledge. Coincidentally, version 4 of RxJS had a trampoline for observable-yielding generators called spawn. It appears to have unceremoniously fallen out of the library. I suspect not enough people were using it. Some people actually prefer the chaining of operators on observables, but if my observables look like promises (i.e. they yield exactly one value or throw an error) but cancelable, then I would prefer syntax like async functions for the same reason it made promises easier to use: it feels more like familiar synchronous programming, making it easier to read and write.

The good news is that generators give us an opportunity. Much like async functions are derived from a combination of promise-yielding generators and a special trampoline, we can define our own trampoline for observable-yielding generators.

Take a step back and think of the generator function. It takes some arguments and returns a generator object. It has a name that I can call when I’m ready to start the generator, and I can call it from many different places, even far from where it is defined. I want to modify my observable-yielding generator functions so that they return an observable instead of a generator object. For that, I need a function that takes the generator function and returns a new function, one that takes the same arguments as the generator function but returns an observable. Further, the generator should not be started when this new function is called, but instead when the observable is subscribed.

We’ll have to define our own kind of observable to implement the trampoline. The easiest way to do that is to shove all the interesting work into a subscriber (not pictured), and then construct the observable with the subscriber:

The subscriber needs to start the trampoline in its constructor, and it needs an unsubscribe method that can stop the trampoline. I’m not going to step through the whole subscriber here, so I’ll just link it for the advanced audience interested in seeing how it works. With async, we can write functions that handle cancelable requests in the framework of observables:

In fact, implementing spawn from RxJS 4 becomes trivial. It just wraps a zero-argument generator function with async and immediately invokes it:

MobX

Now I want to talk about a different kind of observable, those of MobX.
(If you’re unfamiliar, I’m going to have to defer to their documentation.) Mutations of MobX observables should be batched within actions. Async functions do not play well with this practice, but MobX offers an
alternative built on top of generators: flow. The problem is that flow only works with promise-yielding generators, and promises are not cancelable. If we’re using cancelable observables, then we need a flow alternative
that works with them.

Fortunately, it can be easily built on top of the same subscriber that we used for async. All we have to do is wrap each generator method (next, throw, and return) in an action:

Caveats

Async functions are not a panacea for observables, however. Some of the more advanced operators can be difficult or ugly to implement as async functions, especially the ones that carry state, e.g. debounceTime or distinctUntilChanged. If you have a chain of functional staples, though, like map, filter, and catchError, then it is much better written as an async function, in my experience.

how hackers start their afternoons.

John Freeman

Written by

HackerNoon.com
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade