The RxJs Operators I Use Most Often

Taylor Ackley
2 min readMay 27, 2021

When I think of RxJs, I recall a quote from the late great Anthony Bourdain on China.

The one thing I know for sure about China is, I will never know China. It’s too big, too old, too diverse, too deep. There’s simply not enough time.

The same could be said for the impressive breadth and power of RxJs’s deep catalog of operators.

If you are new to RxJs and might be curious what benefits can be had from Reactive programming I suggest this well-written article from This Dot Media.

It's also helpful to have a good understanding of the lifecycle of observables and knowing how long you need to subscribe to a given observable. Ben Lesh (RxJs team member) wrote a highly informative article on this topic.

With all that out of the way, let’s get to the good stuff.

first

I use this one most often. It’s similar to take(1) and will take the first emitted observable and then unsubscribe for you.

Unlike the takeoperator, firstcan also take an optional predicate.

Consider the following example where we don’t want to take a value until the user has been initialized with an auth ticket.

this.userService.getCachedUser().pipe(first(user => user.hasAuthTicket)).subscribe(user => setUser(user));

Compare this to the next example which will simply grab the first value come what may.

this.userService.getCachedUser().pipe(first()).subscribe(user => setUser(user));

RxJs Documentation

takeUntil

first is great if you need to pull the value only once, but if you need the subscribe to last for the entire lifecycle of your component then takeUntil is your huckleberry.

Consider this example

RxJs Documentation

switchMap

I live and die by switchMap and I am a proud graduate of the “switchMap your way to success” school of thought.

Put simply, switchMap allows you to swap out one observable for another. Let’s say you need to get some setup data such as an auth ticket in order to do an HTTP call that returns an observable. You could nest the observables, but it's cleaner to use switchMap.

Consider this example (originally posted here)

RxJs Documentation

skipUntil

By now, this one should be obvious. skipUntil takes a predicate that will filter any new values until the predicate is met. It’s somewhat similar to first except we will continue to receive new values beyond the first value.

Consider this example where we combine the takeUntil operator.

this.userService.getCachedUser().pipe(skipUntil(user => user.hasAuthTicket), takeUntil(this.$unsubscribe)).subscribe(user => setUser(user));

--

--