Can You Autorun RxJS?

Kostia Palchyk
The Startup
Published in
3 min readNov 17, 2020

--

Hey, RxJS streamers! 🙋‍♂️

Today we’re going to review a small library that re-evaluates an expression based on updates in streams it uses.

tl;dr: docs and package at github.com/kosich/rxjs-autorun 🔗

Let’s boldly explore it!

It’s a sweetened countdown

Our first example! A simple mapping

Say, we want to prettify each value on a timer stream. So we’ll write such an expression:

Explanation: computed takes a function that uses some streams and re-evaluates it when those streams update. It returns an observable that you can manipulate further. And $(a) indicates that a is a stream and its updates should be listened to.

So technically this expression is equivalent to a.pipe( map(x => x + '🍰') )

But let’s keep discovering what else this tiny lib can do:

Infinite monkey theorem needs infinite bananas

Our second example. Combine two streams

Here we’ll combine a timer that would represent a queue of our little 🐒 fellas with a stream of fetched bananas 🍌:

BTW, did you know that banana is technically a berry?

Not hard at all, is it? This expression is similar to:
combineLatest(a, b).pipe(map( ([x,y]) => x + y) )

Now let’s review another multiple streams example:

Who’s up to some pizza?

Third example. Reading latest values while not reacting to updates

The last trick we’re gonna learn today is the ability to read the latest values without tracking their updates:

Explanation: _ function indicates that we need to take one value from a stream, but we don't want to recalculate our expression when this particular stream emits. So if an expression uses $(a) and _(b) — it would react only to a updates.

This also means that the computed(() => _(a)) expression would emit one value and immediately complete.

Okay, one really last thing before we wrap-up:

Transformation

Fourth example. Conditionally read values from streams

This time, try to guess what it is:

Indeed, this weather is capricious 🙂

I won’t explain this example in detail, I’m sure by now you can deduce it ;)

Outro 😳

Phew

All the examples shown above you can try here.

And there’s more to the library! Go explore it yourself!

In the following articles, we’ll review how to filter emissions and how to manage subscriptions inside rxjs-autorun expressions. Not to miss those and other RxJS posts — follow me here and on twitter!

If you enjoyed reading — please, indicate that with the 👏 button — it helps a lot!

Thank you for reading this article! Stay reactive and have a nice day 🙂

Also, I want to thank @fkrasnowski for lengthy discussions of this idea, @ryansolid for giving it a try, and Johan for collaborating with me on this! 🙏

--

--