#Is the .pipe operator in rxjs analogous to .then when using promises?

13 messages · Page 1 of 1 (latest)

normal sentinel
#

Title basicially says it all. I got this pseudo example from someone on the Angular discord:

const itemCount$ = merge(
  incrementingThingHappened$.pipe(map(() => 1), 
  decrementingThingHappened$.pipe(map(() => -1)
).pipe(
  // ^ whenever any of those things happen
  scan((count, change) => count + change, 0)
  // ^ increment the value
);

The annotation "whenever any of those things happen" makes it sound like .pipe acts pretty much in the same way as how .then is used when chaining promises, except that .pipe wraps the to be chained function in a transformation.. decorator i suppose? I assume as to standardize some common access patterns to piped data?

Either way I can run a function via scan which to me is analogous to writing a chained promise.

quiet ermine
#

@normal sentinel I think the most analogous thing to .then is .map:

of(1,2,3)
  .pipe(map(x => x + 1))
  // logs 2,3,4
  .subscribe(out => console.log(out))
#

The point of pipe itself is fairly subtle. You could imagine that methods like .map were directly attached to the observable:

of(1,2,3)
    // Not actual API, but it 'could be'
   .map(x => x + 1)
   .subscribe(out => console.log(out));
#

But I think the main point of pipe is that it's easier to abstract things out:

const addOne = map(x => x + 1);

const moreOperations = [ filter(x => x > 2), map(x => x * 2) ];

of(1,2,3)
   .pipe(addOne, ...moreOperations)
   .subscribe(out => console.log(out));
normal sentinel
quiet ermine
#

It takes multiple arguments, yeah.

normal sentinel
normal sentinel
quiet ermine
#

Yeah. It looks like in older versions of RxJS the operators were directly attached to the observables.

normal sentinel
#

as opposed to .then where you need to define any chain of functions in a verbose way, i.e. one at a time like .then().then().then() ...

normal sentinel
#

its kind of stupid that the docs dont mention the different variations of pipe or offer a quick and simple explanation on what it does

#

but thx, that solved my question