20 Apr 2020
3 min

Create a tapOnce custom Rxjs Operator

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.

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 behaviour, 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.

Using defer

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:

StackBlitz

Frequently asked questions

How do I create a tapOnce operator in RxJS?

Create a custom operator that uses defer() to build a fresh tap() pipeline for each subscription, then run the callback only while a per-subscription first flag is true. Set the flag to false after the first emission. This invokes the side effect once without changing or stopping the source stream.

Why should I use defer() when writing a custom RxJS operator?

Use defer() to create the observable inside the subscription, rather than subscribing to the source while the operator is being set up. Each subscription gets a fresh first flag, and the callback runs only if that subscription receives a value. This also avoids a hidden inner subscription that could run before the downstream stream is subscribed.

Does tapOnce run once per observable or once per subscription?

The tapOnce implementation using defer() runs its callback once per subscription, on that subscription’s first emission. Subscribing twice creates separate state, so each subscription can trigger the callback independently. The earlier approach that subscribes internally does not have this behavior and can run its side effect even when the returned observable is never subscribed.

What is the difference between tapOnce and take(1) in RxJS?

tapOnce runs a side effect on the first emission and then lets later emissions continue through the stream. take(1) instead limits the stream to its first emission and completes it. Using take(1) inside a separate subscription can create an unintended subscription, so it does not provide the same behavior as a tapOnce operator built with defer().

Does tapOnce respect takeUntil in an RxJS pipe?

A tapOnce built with defer() respects downstream unsubscription from takeUntil: if the notifier emits before the source’s first value, the callback does not run. An implementation that creates its own inner subscription does not know about the later takeUntil in the pipe, so its side effect may still execute.

Share this post

Sign up for our newsletter

Stay up-to-date with the trends and be a part of a thriving community.