In my Angular/Typescript project, I am dealing with 2 subscriptions. Each subscription is subscribing to its own observable A
and B
, which are located outside the component in the service file.
Sometimes, when A
changes, B
may or may not change based on certain component actions, and vice versa. Typically, B
changes after A
changes in another component.
In addition, B
must perform an action only after verifying the correct value of A
. My initial approach involved nested subscriptions with an if statement as shown below:
ngOnInit(){
this.A = this.serviceX.a.subscribe(
data =>{
this.temp = data;
if(data=='correct'){
this.B = this.serviceX.b.subscribe(
beta => {
console.log('Sure'+this.temp);
}
)
}
}
)
}
Although this approach works, I have come across posts suggesting it may not be the most efficient way. Thus, I experimented with combineLatest
and forkJoin
, but found that they only trigger if both observables change simultaneously. If one observable remains unchanged, these operators do not execute. Please correct me if I'm mistaken.
Currently, my solution involves separate subscriptions executed sequentially like so:
this.A = this.serviceX.a.subscribe(
data =>{
this.temp = data ;
}
)
this.B = this.serviceX.b.subscribe(
beta =>{
if(this.temp=='correct'){
console.log('Sure'+this.temp)
}
}
)
However, I am concerned about potential instability in this method. Which RxJS operator should I utilize to ensure that subscription B only occurs after A has completed changing (even though A may not change at times), thereby enhancing the overall robustness of the procedure?