Unsubscribing an array of subscriptions

In an Angular app, I manage my subscriptions by pushing them all into an array, then iterating over it and unsubscribing in time ngOnDestroy

.

private subscriptions: Subscription[] = []
this.subscriptions.push(someObservable.subscribe(foo => bar))

      

My problem is that I haven't found a clean enough way to handle unsubscribe. The ideal path would be easy

ngOnDestroy () {
    this.subscriptions.forEach(subscription => subscription.unsubscribe())
}

      

but it doesn't work. Notably, I still get Firebase permission errors after logging out (which does not happen with "working" methods). Interestingly, the same method works if I pull it out into a separate class:

export class Utils {
    public static unsubscribeAll (subObject: {subscriptions: Subscription[]}) {
        subObject.subscriptions.forEach(subscription => subscription.unsubscribe())
    }
}

// ---------- back to the component

ngOnDestroy () {
    Utils.unsubscribeAll({subscriptions: this.subscriptions}) // no Firebase errors
}

      

but I don't really like this solution, mainly because it only works if I wrap the array in an object so that it is passed as a reference. Another working method I found was to write it as a for loop:

ngOnDestroy () {
    /* tslint:disable */
    for (let i = 0; i < this.subscriptions.length; i++) {
        this.subscriptions[i].unsubscribe()
    }
    /* tslint:enable */
}

      

but aside from the unnecessary length, this also makes TSLint complain because it thinks I should use a for-loop instead (it doesn't work), so I have to add additional comments every time.

I am currently using the Utils option as the "best" solution, but I am still not happy with it. Is there a cleaner way to do this that I am missing?

+3


source to share


1 answer


Since nobody wants to post their answer as an answer, I think I will.

If you are using a grouping array for bulk unsubscribe, you can do the same by concatenating them into an existing subscription. For my setup, just change the empty array to an empty subscription and change push

to add

:

private subscriptions = new Subscription()
this.subscriptions.add(someObservable.subscribe(foo => bar))

      



Then when you want to unsubscribe from them, just unsubscribe from the container and it will handle everything.

ngOnDestroy () {
    this.subscriptions.unsubscribe()
}

      

Note. You can also use takeUntil

for each individual subscription, but I feel like this method is simpler and makes more sense for what I am doing.

+6


source







All Articles