Angular/RxJs When should I unsubscribe from `Subscription`

前端 未结 22 2854
隐瞒了意图╮
隐瞒了意图╮ 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:19

    Since seangwright's solution (Edit 3) appears to be very useful, I also found it a pain to pack this feature into base component, and hint other project teammates to remember to call super() on ngOnDestroy to activate this feature.

    This answer provide a way to set free from super call, and make "componentDestroyed$" a core of base component.

    class BaseClass {
        protected componentDestroyed$: Subject = new Subject();
        constructor() {
    
            /// wrap the ngOnDestroy to be an Observable. and set free from calling super() on ngOnDestroy.
            let _$ = this.ngOnDestroy;
            this.ngOnDestroy = () => {
                this.componentDestroyed$.next();
                this.componentDestroyed$.complete();
                _$();
            }
        }
    
        /// placeholder of ngOnDestroy. no need to do super() call of extended class.
        ngOnDestroy() {}
    }
    

    And then you can use this feature freely for example:

    @Component({
        selector: 'my-thing',
        templateUrl: './my-thing.component.html'
    })
    export class MyThingComponent extends BaseClass implements OnInit, OnDestroy {
        constructor(
            private myThingService: MyThingService,
        ) { super(); }
    
        ngOnInit() {
            this.myThingService.getThings()
                .takeUntil(this.componentDestroyed$)
                .subscribe(things => console.log(things));
        }
    
        /// optional. not a requirement to implement OnDestroy
        ngOnDestroy() {
            console.log('everything works as intended with or without super call');
        }
    
    }
    

提交回复
热议问题