Home > front end >  Concerned about subscribing twice with the same code and then unsubscribing
Concerned about subscribing twice with the same code and then unsubscribing

Time:11-12

Lets say I have a function like below that gets called by a button click in my component.

  1. What happens if I click my button twice to the first and second subscriptions?
  2. What happens if I click my button twice and then unsubscribe mySub in my ngOnDestroy()?
  3. If the function has potential to be called twice, should I add logic in myFunction() to unsubscribe from my first subscription before subscribing again?
mySub: Subscription;

myFunction(){

    this.mySub = this.myService.getSomeData(this.data).subscribe({
        next: (val) => { 
            //stuff
        },
        error: (e) => { 
            //more stuff
        }
    });

}

I'm thinking that if there's potential for a subscription to be executed twice then I should unsubscribe before making another subscription.

CodePudding user response:

I might be wrong here but I believe...

  1. You will have 2 subscriptions
  2. Only the current instance of mySub will be unsubscribed

3....

Instead, I would declare a subject in the component and next it when the button is clicked. In your ngOnInit subscribe to the that subject and mergeMap it to the getSomeData observable. Something like this:

export class myComponent implements OnInit, OnDestroy {
  private mySubj = new Subject<null>()
  private sub: Subscription | null = null
  ngOnInit() {
    this.sub = this.mySubj.pipe(
      mergeMap(() => this.myService.getSomeData
    ).subscribe(() => {
       // Do the thing 
    })
  }

  onButtonClick() {
    this.mySubj.next(null)
  }

  ngOnDestroy() {
    this.sub?.unsubscribe()
}

I'm on mobile so please excuse any typos. Will edit if pointed out

  • Related