rxjstapfinalize

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


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
            })
        })
    )

Solution

  • 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.