Can You Autorun RxJS?
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:
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 🍌:
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:
_ 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
_(b) — it would react only to
This also means that the
computed(() => _(a)) expression would emit one value and immediately complete.
Okay, one really last thing before we wrap-up:
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 ;)
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 🙂
Psst.. need something more to read?
I got you covered:
- “Turn a Stream of Objects into an Object of Streams”
- “Fetching Data in React with RxJS and <$> fragment”
- “Queries for Observables: Crazy & Simple!”
- “Intro to Recks: Rx+JSX experiment”