Search code examples
rxjsngrxngrx-effects

Is there an operator that lets me keep the initial value from a subscription after executing ,, switchMap"?


I try to have access to the value emitted by the initial Observable after switchMap, inside the map operator.

https://ibb.co/1QB9zZp

I have looked at other operators, but i didn't find out any solution.


Solution

  • Here's an operator for RxJS that will emit both the outer value and inner value as an array pair [outer, inner].

    Here's a switchMap() variant.

    export function withSwitchMap<T, R>(inner: (T) => Observable<R>): OperatorFunction<T, [T, R]> {
        return (source: Observable<T>): Observable<[T, R]> => {
            return source.pipe(
                switchMap(a => inner(a).pipe(map(b => [a, b] as [T, R])))
            );
        }
    }
    

    Here's a mergeMap() variant.

    export function withMergeMap<T, R>(inner: (T) => Observable<R>): OperatorFunction<T, [T, R]> {
        return (source: Observable<T>): Observable<[T, R]> => {
            return source.pipe(
                mergeMap(a => inner(a).pipe(map(b => [a, b] as [T, R])))
            );
        }
    }