RxJS finalize operator vs tap({ finalize: () => {} })

1.5k Views Asked by At

Is there any difference between A and B? Are there any cases where one would behave differently than the other?

A)

observableHere
    .pipe(
        finalize(() => {
            // Do stuff here
        })
    )

B)

observableHere
    .pipe(
        tap({
            finalize: () => {
                // Do stuff here
            })
        })
    )
2

There are 2 best solutions below

1
Mrk Sef On BEST ANSWER

Tap lets you hook into a bunch of events on the source observable

interface TapObserver<T>: {
   next: (value: T) => void;
   error: (err: any) => void;
   complete: () => void;
   subscribe: () => void;
   unsubscribe: () => void;
   finalize: () => void;
}

If you're producing side effects for an observable's various emissions, it might be easier to group them all together in a single TapObserver. Otherwise, just using the finalize operator is probably clearer.


Are there any cases where one would behave differently than the other?

They shouldn't behave any differently.

0
Matthieu Riegler On

Finalize in tap makes absolutly no sense to me.

The only difference is that it will be called before the final finalize.