Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Asynchronous equivalent to tap() in RxJS?

I have a side effect Observable that's required to be resolved before the main Observable is completed. If it were a synchronous operation, I could use the tap() operator. Is there a clear equivalent for an asynchronous operation?

In the following example, I have to map the inner value back to the outer value I actually want to pipe through. How would I avoid this mapping?

  const user = requestUser().pipe( 
    switchMap(user => {
      return requestAndAssignToken(user)
        .pipe(
          map(token => user)
        );
    })
  );
like image 539
MattTreichel Avatar asked Nov 14 '18 18:11

MattTreichel


People also ask

What is TAP () in RxJS?

RxJS tap() operator is a utility operator that returns an observable output that is identical to the source observable but performs a side effect for every emission on the source observable.

What is asynchronous in RxJS?

async scheduler schedules tasks asynchronously, by putting them on the JavaScript event loop queue. It is best used to delay tasks in time or to schedule tasks repeating in intervals.

What is the difference between tap and map?

The map operator will simply apply a function to that data and return the result. The tap operator however takes a data, apply a function to that data but returns the original data, if the function bothered to return a result, tap just ignores it.

Are RxJS observables async?

A common misconception in Angular development is regarding whether observables are synchronous or asynchronous. A lot of (even experienced Angular developers) think that observables are async, but the truth is that they can be… Both synchronous and asynchronous.


1 Answers

If I understand correctly, you want to ignore the result of the inner Observable and just have the outer Observable wait for it to emit before moving on.

In that case, I'd suggest the delayWhen operator. It is passed a delayDurationSelector that returns an Observable (the duration Observable). It then behaves like stated in the documentation:

The source value is emitted on the output Observable only when the duration Observable emits a value or completes

For your example, it would look like this:

const user = requestUser().pipe( 
    delayWhen(user => requestAndAssignToken(user))
);

Here is a simple example

like image 150
ggradnig Avatar answered Sep 21 '22 10:09

ggradnig