Kevin Beal
Kevin Beal

Reputation: 10858

Observable operator for pulling out value for later

I'm using observables with the RXJS library and have a situation where I want to pull out a value and use it at an unspecified time in the future that is not the next operator or the subscribe method.

I am currently passing the value through every operation until I need it. Something that looks like this:

obsveable$.pipe(
    ofType('example'),
    map((action) => [
        action, // <-- passing this through
        somethingElse
    ]),
    map(([action, other]) => [
        action, // <-- through again
        anotherThing
    ]),
    map(([action, other]) => {
        // finally use action
    }),
);

I could maybe try saving it to a local variable – something like this:

let action;
obsveable$.pipe(
    ofType('example'),
    map((_action) => action = _action),
    map((action) => action.somethingElse),
    map((other) => {
        // finally use action
    })
);

Both of these solutions are suboptimal. The first gets unwieldy when there are a lot of steps and the second is subject to possible order of operations issues (and it's not using the cool reactive approach).

What other options are there?

Upvotes: 0

Views: 38

Answers (1)

ZahiC
ZahiC

Reputation: 14697

You can create a closure this way:

obsveable$.pipe(
    ofType('example'),
    mergeMap(action => 
        Observable.of(somethingElse)
            .pipe(
                map(other => anotherThing), 
                map(other => { 
                    // use action
                })
            )
    )
);

Upvotes: 2

Related Questions