After conducting a thorough search, I couldn't find a similar question to mine, so I apologize if this has been asked before.
In my scenario, I have multiple connected observables working in sequence.
One of the observables, let's call it Observable A, triggers another observable, Observable B, using switchmap.
The interesting thing about Observable B is that it functions as a Behavior Subject, although this detail might not be crucial for the issue at hand.
Observable B doesn't complete its operation; instead, it continuously emits either true or false values.
When Observable B receives a true value, it calls yet another observable, Observable C, through switchmap. This chain keeps going on and on.
What I'm aiming for is when Observable B receives false, it should do nothing (which currently works fine). However, when it receives true, it should trigger Observable C (also functioning correctly). The challenge arises because Observable B never completes, leading to an endless loop. How can I make Observable B complete or unsubscribe from it without interrupting the subsequent chain of events? I want the chain to restart whenever Observable B receives a .next(true) rather than continuing indefinitely.
I tried utilizing 'takeUntil' by passing an observable that triggers upon receiving a true value. However, everything abruptly ended, and my main subscription didn't receive any data (Observable C and beyond did not execute).
Below, you'll find some code snippets with certain logic removed:
private initMap(): Observable<boolean> {
return this.platformHelperService.getUserLocation().pipe(
switchMap(_ => {
return this.updateMapCenterLocation();
public updateMapCenterLocation(): Observable<boolean> {
let mapCenterSetObserver: Observer<void>;
const mapCenterSetObservable = Observable.create(
(observer: Observer<void>) => {
mapCenterSetObserver = observer;
}
);
// This corresponds to Observable B
return this.mapAssignedBehaviorSubject.pipe(
switchMap(assigned => {
if (assigned) {
// Observable C implementation below. Additional tasks are performed after completion.
return this.platformHelperService.getUserLocation()
// Executing the lines below causes the initial subscription to instantly finish with Observable C failing to run.
// Omitting these lines leads to Subscription B never reaching completion.
mapCenterSetObserver.next(undefined);
mapCenterSetObserver.complete();
}
}),
takeUntil(mapCenterSetObservable)
);
}