Create a tapOnce custom Rxjs Operator

joaquin cid
Angular In Depth
Published in
4 min readApr 21, 2020

AngularInDepth is moving away from Medium. This article, its updates and more recent articles are hosted on the new platform inDepth.dev

If you use rxjs on your project you most likely are using the tap operator.
tap does not change the stream and allows you execute a function (or side-effect) taking as parameter the value of each emission. For instance we can console.log each emitted value like this:

source.pipe( tap(val => console.log(val)) );

What happens if we want to execute a side-effect but only on the first emission? rxjs does not include an operator for this, but no worries, we can write our own!

Writing a custom operator #

If you are not familiar with the internals of an rxjs operator, in a nutshell an operator is just a function that takes an observable and returns an observable. That's it.
Most of the times we'll transform the observable before we return it or do something with it. If you want to read more on writing custom operators you can check this post or this one.
So, following this guideline this is a how a basic custom operator would look like.

function basicCustomOperator<T>() { return function(source: Observable<T>) { return source; }; }

And we can use it like this:

source.pipe( basicCustomOperator() )

Now that we have the ground base of a custom operator, let’s write tapOnce.

An initial approach could be to use the existing take operator. We would apply take(1) on the source observable and create an inner subscription on it. We will then return the original source back to the stream.

function tapOnce<T>(fn: (value)=> void) { return function(source: Observable<T>) { source .pipe( take(1), tap(value => fn(value)) ) .subscribe(); return source; }; }

This approach seems ok, and will work for most cases, but has some problems.
First, it will create a subscription on the source. This could lead to unexpected behaviours, like executing the side-effect even if we never we subscribe to the original observable.

const sourceSubject = new Subject(); const source = sourceSubject.pipe( tapOnce(x => console.log(`tapOnce ${x}`)), ); sourceSubject.next("1"); sourceSubject.next("2"); // tapOnce will execute even if we didn't subscribe to sourceSubject

Also, since we are using the reference of the source if we subscribe multiple times, it will only execute once.

const sourceSubject = new Subject(); const source = sourceSubject.pipe( tapOnce(x => console.log(`tapOnce ${x}`)) ); source.subscribe(); source.subscribe(); sourceSubject.next("1"); sourceSubject.next("2"); // tapOnce will execute on first subscribe, when we would expect to run for both

Another problem is when you combine the stream with takeUntil operator.

source.pipe( tapOnce(x=> console.log(`tapOnce ${x}`)), takeUntil(takeUntilSource) ).subscribe(x=> console.log(x)) source.subscribe(); takeUntilSource.next() source.next('1') source.next('2') source.next('3')

takeUntil happens before first source emission, and we would expect tapOnce to not execute at all, but indeed it emits. The reason for this is that we have an inner subscription in our custom operator that doesn't know about our takeUntil we have later in the pipe.

Let’s see how we can fix this. What we need is an operator that allows us to run our code only when the original source is subscribed, and also that wont share the execution context if multiple subscriptions occur. Luckily rxjs includes the defer operator that helps us with this.
So, this would be the refactored version of tapOnce:

function tapOnce<T>(fn: (value) => void) { return (source: Observable<any>) => defer(() => { let first = true; return source.pipe( tap<T>((payload) => { if (first) { fn(payload); } first = false; }) ); }); }

Let’s dissect the code to understand what’s going on. We are returning a defer() observable, which creates an observable only when it is subscribed.

defer(() => { // ... return source.pipe( // ... ); });

Also it creates a fresh observable for each subscription, keeping its state “per-subscription”. We want this to be sure each subscription will have its own value of first variable. You can read more about this here

Finally we are just checking if it is the first emission and run the function or not.

// ... let first = true; return source.pipe( tap((payload) => { if (first) { fn(payload); } first = false; }) );

Now, we have a tapOnce operator that works for all scenarios as expected!

Hope you enjoyed the post! You can play with the code here:

Originally published at https://indepth.dev on April 21, 2020.

--

--