Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2194
隐瞒了意图╮
隐瞒了意图╮ 2020-11-21 04:56

When should I store the Subscription instances and invoke unsubscribe() during the NgOnDestroy life cycle and when can I simply ignore them?

22条回答
  •  北荒
    北荒 (楼主)
    2020-11-21 05:15

    A Subscription essentially just has an unsubscribe() function to release resources or cancel Observable executions. In Angular, we have to unsubscribe from the Observable when the component is being destroyed. Luckily, Angular has a ngOnDestroy hook that is called before a component is destroyed, this enables devs to provide the cleanup crew here to avoid hanging subscriptions, open portals, and what nots that may come in the future to bite us in the back

    @Component({...})
    export class AppComponent implements OnInit, OnDestroy {
        subscription: Subscription 
        ngOnInit () {
            var observable = Rx.Observable.interval(1000);
            this.subscription = observable.subscribe(x => console.log(x));
        }
        ngOnDestroy() {
            this.subscription.unsubscribe()
        }
    }
    

    We added ngOnDestroy to our AppCompoennt and called unsubscribe method on the this.subscription Observable

    If there are multiple subscriptions:

    @Component({...})
    export class AppComponent implements OnInit, OnDestroy {
        subscription1$: Subscription
        subscription2$: Subscription 
        ngOnInit () {
            var observable1$ = Rx.Observable.interval(1000);
            var observable2$ = Rx.Observable.interval(400);
            this.subscription1$ = observable.subscribe(x => console.log("From interval 1000" x));
            this.subscription2$ = observable.subscribe(x => console.log("From interval 400" x));
        }
        ngOnDestroy() {
            this.subscription1$.unsubscribe()
            this.subscription2$.unsubscribe()
        }
    }
    

提交回复
热议问题