angularrxjsconcatmap

How do I subscribe in sequence and return only the value from the last observable in RxJS?


I'm in an Angular route resolver and want to return an observable.

I need to subscribe to multiple async processes in order:

A => B(a) => C(b)

C depends on B and B depends on A. A must complete, then B, then C, but I only want the value from C to be used to cause the route to resolve.

I've tried two different approaches:

return A.pipe(
  concatMap(a => 
    B(a).pipe(
      concatMap(b => 
        C(b).pipe((c) => c); // also tried of(c)
      )
    )
  )
);

I've also tried

return A.pipe(
  concatMap(a => {
    return B(a).pipe(map(b => {a: a, b: b});
  ),
  concatMap({a, b} => {
    return C(b);
  )
);

How do I subscribe to A, then B, then C ..., and then only get the value from the innermost observable?

If I put a tap after my last concatMap I get my expected return value. But my resolver never resolves? (or the wrong thing is getting emitted? I cannot really tell.)


Solution

  • Route resolvers need to complete before the Angular Router will continue. This is the same for route guards also. Adding a operator that takes an emission, such as take(1), or first() and completes will solve the problem.

    return A.pipe(
      concatMap(a => {
        return B(a).pipe(map(b => {a: a, b: b});
      ),
      concatMap({a, b} => {
        return C(b);
      ),
      take(1)
    );