Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to wait for promise resolve rxjs filter

In my observable source I receive events in which I want to filter for a certain async operation.

For instance:

s$.pipe(
    map((x) => x + 1),
    filter((x) => alreadyExist(x)))
  .subscribe(...)

When alreadyExist is an async operation,
(checking if the value exist in a persistent storage) which returns a boolean.

Assume alreadyExist return a promise which resolve to a boolean,
how can I wait on the return?
Note that I need the value not to change.
Doing async-await didn't work and the subscribe executed before the filter returned.

like image 680
itaied Avatar asked Sep 14 '25 16:09

itaied


1 Answers

If alreadyExist returns a boolean you can use mergeMap that will wait for its result and if it's true than it'll map it into the original x value. When it's false then it's just filtered out by filter.

s$.pipe(
    map((x) => x + 1),
    mergeMap(x => from(alreadyExist(x)).pipe(
      filter(Boolean),
      mapTo(x),
    )),
  )
  .subscribe(...)
like image 64
martin Avatar answered Sep 17 '25 04:09

martin