Lets say I have a function like below that gets called by a button click in my component.
- What happens if I click my button twice to the first and second subscriptions?
- What happens if I click my button twice and then unsubscribe
mySub
in my ngOnDestroy()? - 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...
- You will have 2 subscriptions
- 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