Unsubscribing an array of subscriptions

后端 未结 2 679
粉色の甜心
粉色の甜心 2021-02-02 15:40

In an Angular app, I\'m managing my subscriptions by pushing them all into an array, then looping through it and unsubscribing during ngOnDestroy.

p         


        
相关标签:
2条回答
  • 2021-02-02 16:04

    Since nobody wants to post their answer as an answer, I guess I'll do it.

    If you're only using the array to group them for mass unsubscribing, you can accomplish the same thing by merging 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 all, just unsubscribe from the container subscription and it will handle everything.

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

    Note: you can also use takeUntil on each individual subscription, but I feel like this method is simpler and makes more sense for what I'm doing.

    0 讨论(0)
  • 2021-02-02 16:15
    subs: Subscription[] = [];
    
    ngOnInit(): void {
        this.subs.push(someObservable.subscribe(foo => bar));
    }
    
    ngOnDestroy(): void {
        this.subs.map(s => s.unsubscribe);
    }
    
    0 讨论(0)
提交回复
热议问题