Search code examples
rxjsrxjs-pipeable-operators

Can I keep track of a value when using pipeable operators?


Is there a way to keep track of a value with pipeable operators?

To give a tangible example, let's say that I want to :
Over a data stream S:

  1. Memorize S current data
  2. Make a HTTP request
  3. Do stuff with the response
  4. Make another HTTP request using the result of the operation
  5. Create an object containing a value base on 1. and the response

Then merge these and exploit the objects I created.

Basically,

const data = from([1, 2, 3]).pipe(
  // Memorize here
  map(a => req1(a)),
  flatMap(a => a),
  map(b => syncOp(b)),
  map(c => req2(c)),
  flatMap(d => d),
  map(e => ({id: _memorized_, value: e}))

merge(data).subscribe(f => console.log(f.id, f.value))

Related stackblitz

Any input on the matter will be greatly appreciated.


Note: If possible, I'd prefer not to carry the value I need all the way down via the creation of an object at the top.


Solution

  • You can easily do that by just restructuring your operators and making memorized a local variable:

    const data = from([1, 2, 3]).pipe(
      // Memorize here
      mergeMap(memorized => req1(memorized).pipe(
        flatMap(a => a),
        map(b => syncOp(b)),
        map(c => req2(c)),
        flatMap(d => d),
        map(e => ({id: memorized, value: e}))
      ));
    
    merge(data).subscribe(f => console.log(f.id, f.value));