Reputation: 6857
Within my Angular app :
i ve this treatment :
mySubjectOne = new Subject();
methodOne(){
this.subscriptionOne = mySubjectOne.subscribe((response) => {
this.methodTwo();
})
}
methodTwo(){
this.subscriptionTwo = return this.httpClient.post(myurl , mydata).subscribe((response) => {
myTreatment(); // MY TREATMENT
})
}
My probleme is whenever "mySubjectOne " is called methodOne calls methodTwo ,
and the subscriptionTwo seems to be cloned to be +1 every time :
for example in the third time of calling : methodOne , it seems that there were 4 subscriptionTwo invoqued
How may i close the subsrciption subscriptionTwo just after TREATMENT and let it be recreated in each rime
Suggestions ?
Upvotes: 0
Views: 165
Reputation: 5482
You can use switchMap to achieve exactly this behavior.
Note that there are also other operators such as exhaustMap
or mergeMap
that may fit your desired behavior even more. Read up on the source provided.
mySubjectOne = new Subject();
methodOne() {
this.subscriptionOne = mySubjectOne.pipe(
switchMap((response) => this.methodTwo()),
)
.subscribe((response) => {
myTreatment();
});
}
methodTwo() {
this.subscriptionTwo = return this.httpClient.post(myurl , mydata);
}
Now whenever mySubjectOne
fires, methodTwo
will be executed. Once that's done, myTreatment
will run.
Note that you should run methodOne
just once (to initialize the subscription), as otherwise the subscription may run multiple times.
So I suggest to move the initialization process into your constructor or maybe ngOnInit
.
Upvotes: 2