RaidenF
RaidenF

Reputation: 3521

Cancel subscription, when subscribing two observables to each other

I have two observables, that never complete (they are event handlers). Every time that observable A emits, I want to discard all emissions of B, wait for B to emit a value, and do something with A's emission; ignore further B emissions. If A emits a second time, while waiting for B, I want to cancel waiting.

Currently I have the following code:

obsA$.subscribe(value => {
  obsB$.pipe(take(1)).subscribe(_ => {
    if (value) {
        // do stuff with value
    }
  });
});

This does not cover the case when: A emits once, then A emits again, and then B emits a value, the 1st subscription to B should be cancelled, and only the second subscription should execute.

How should I approach this issue? Is there some better / clearer way to write this?


ObservableA is a navigation event (navigation to a new address), and ObsB is from an animation event, that happens after navigation. When navigating to a new address, I want to wait for the animation to complete, and then do something.

Upvotes: 0

Views: 244

Answers (1)

martin
martin

Reputation: 96891

It looks like you're describing switchMap that always subscribes to the Observable returned from its callback and unsubscribes from the previous one.

obsA$
 .pipe(
    switchMap(v => obsB$.pipe(mapTo(v))), // pass through only the original emission from obsA$
  )
  .subscribe(resultFromA => ...);

Upvotes: 2

Related Questions