DEV Community

Kwinten Pisman for Strongbrew

Posted on • Originally published at blog.strongbrew.io

RxJS examples of the day (part 1)

Having worked with and teaching RxJS for quite some time now, I always felt that the way RxJS is explained is very theoretical. For that reason, I started tweeting out these practical RxJS examples that I basically plucked from my own codebases.
This blog post will hopefully be part of a series (depending on my inspiration ☺️). Here are the first 5.

Handle replaying of keydown events

The browser replays 'keydown' events for as long as the user keeps pressing the button. Often times, you just want to have the 'keydown' event as a trigger but want to remove the duplicate ones without constantly removing and reading the eventlistener.

Using the conditional iif operator

The iif operator helps when your initial stream depends on a condition. Without the operator, we would have to write a pretty ugly (and imperative) 'if-else'.

When and how many times is a stream subscribed to

Knowing when and how many times a stream is subscribed to can be extremely valuable information to have when working with RxJS. If you for instance have multiple backend calls that are triggered, this info can help pinpoint the issue.

Optimising your autocompletes

When the user starts typing, you typically want to remove the existing results in an autocomplete as they don't match what the user was typing no more. You can do this by branching existing streams instead of resorting to side effects or Subjects.

Using exhaustMap as a flattening operator

Sometimes you want to avoid the user constantly canceling calls. If a call is already on it's way, we probably want to continue that one first. Using exhaustMap is the perfect operator for that.

Top comments (0)