Angular/RxJs When should I unsubscribe from `Subscription`

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

    in SPA application at ngOnDestroy function (angular lifeCycle) For each subscribe you need to unsubscribe it. advantage => to prevent the state from becoming too heavy.

    for example: in component1 :

    import {UserService} from './user.service';
    
    private user = {name: 'test', id: 1}
    
    constructor(public userService: UserService) {
        this.userService.onUserChange.next(this.user);
    }
    

    in service:

    import {BehaviorSubject} from 'rxjs/BehaviorSubject';
    
    public onUserChange: BehaviorSubject = new BehaviorSubject({});
    

    in component2:

    import {Subscription} from 'rxjs/Subscription';
    import {UserService} from './user.service';
    
    private onUserChange: Subscription;
    
    constructor(public userService: UserService) {
        this.onUserChange = this.userService.onUserChange.subscribe(user => {
            console.log(user);
        });
    }
    
    public ngOnDestroy(): void {
        // note: Here you have to be sure to unsubscribe to the subscribe item!
        this.onUserChange.unsubscribe();
    }
    

提交回复
热议问题