firasKoubaa
firasKoubaa

Reputation: 6857

RxJs : How to close subscription of nested observable.subscribe call

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

Answers (2)

Philipp Meissner
Philipp Meissner

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

StPaulis
StPaulis

Reputation: 2916

I believe that is a bad idea to subscribe inside a subscription. You better use SwitchMap to handle it.

If you prefer to go your way, you could use TakeUntil to emit the end of your subscription.

Upvotes: 1

Related Questions