I have a service which contains observable as below
private _actionSaveSubject: BehaviorSubject<string> = new BehaviorSubject<string>( null );
actionSave$: Observable<string> = this._actionSaveSubject.asObservable();
private _actionAfterSaveSubject: BehaviorSubject<string> = new BehaviorSubject<string>( null );
In my components (Component1 and Component2) I inject the service and call the actionSave$ as below
this.actionService.actionSave$
.pipe(
takeUntil( this._unsubscribeAll ),
skip(1),
tap(t => {/* TODO saving */ }),
)
.subscribe()
In my service I want to know when both the components have finished their actionSave$ observable so that I can call _actionAfterSaveSubject.next(). Is there anyway I can do that?
CodePudding user response:
If I understood you correctly, you want to perform an action after every of your side-effects (inside tap
) have run. The only reliable way I see to do this is to feed the observables back to the service and combine them there.
@Service({…})
class YourService {
private _actionAfterSaveSubject: BehaviorSubject<string> = new BehaviorSubject<string>( null );
currentSaveSubscription: Subscription;
actionSaveObservables: Observable<any>[] = [];
registerActionSaveObservable(saveObservable: Observable<any>) {
this.actionSaveObservables.push(saveObservable);
if (this.currentSaveSubscription) {
this.currentSaveSubscription.unsubscribe()
}
this.currentSaveSubscription =
zip(...actionSaveObservables)
.subscribe(() => this._actionAfterSaveSubject.next(""))
}
}
And then register your observables in the component.
this.actionService.registerActionSaveObservable(
this.actionService.actionSave$
.pipe(
takeUntil( this._unsubscribeAll ),
skip(1),
tap(t => {/* TODO saving */ }),
)
);