I am faced with a challenge where I have two functions, A and B. My goal is to have both of these functions run when the component loads, specifically on ngOnInit. However, I need function B to only run after function A has completed execution because B relies on values from A. To achieve this, I have encapsulated function B inside function A. Function A involves observables, leading to multiple subscription calls when navigating to different pages and returning back.
Within my code for function A, I need to populate two separate objects - data: any and array1.
Here is an example of the code for function A:
ngOnInit(){
A();
}
A(){
this.service1.getData().subscribe((resp)=>
if(resp){
this.service2.dataFor.pipe(skipWhile((val)=>val ===null )).subscribe((response)=>{
})
}
)
}
B(){
if(this.data && Object.keys(this.data).length>0){
this.service3.getValidity(this.data.data).subscribe((resp)=>{
if(resp){
console.log("from B if");
}
else if(this.array1.length===0){
this.service3.getValidity('').subscribe((res)=>{
console.log("from B else");
})
}
})
}
}
To address the issue of multiple subscription calls, I initially attempted to call function B inside function A like so:
A(){
this.service1.getData().subscribe((resp)=>
if(resp){
this.service2.dataFor.pipe(skipWhile((val)=>val ===null )).subscribe((response)=>{
B();
})
}
)
}
However, this approach resulted in repeated subscription calls. The output was displayed as 'from B if' twice initially, and increased by one upon each navigation to another page and return.
Considering that unsubscribed subscriptions could be the cause, I made sure to include an onDestroy hook:
ngOnDestroy(){
}
The full reference code snippet includes a more structured approach with proper handling of subscriptions:
A(){
this.subscription1=this.service1.getData().subscribe((resp)=>
if(resp){
this.subscription2=this.service2.dataFor.pipe(skipWhile((val)=>val ===null )).subscribe((response)=>{
})
}
)
}
B(){
if(this.data && Object.keys(this.data).length>0){
this.subscription3=this.service3.getValidity(this.data.data).subscribe((resp)=>{
if(resp){
}
else if(this.array1.length===0){
this.service3.getValidity('').subscribe((res)=>{
})
}
})
}
}
ngOnDestroy() {
if (this.subscription1 && !this.subscription1.closed) {
this.subscription1.unsubscribe();
}
if (this.subscription2 && !this.subscription2.closed) {
this.subscription2.unsubscribe();
}
if (this.subscription3 && !this.subscription3.closed) {
this.subscription3.unsubscribe();
}
}
Despite implementing subscription management within onDestroy, the issue persisted. It became evident that the nested function calls of B() inside A() were causing the problem.
My main objective is to ensure that function A completes its task of populating values in data and array1 before invoking function B. How can I achieve this efficiently without facing multiple subscription calls?