Skip to content

Instantly share code, notes, and snippets.

@M3ales
Last active May 11, 2022 23:09
Show Gist options
  • Save M3ales/d8608fc639c706d60bc953c6ee7e3da8 to your computer and use it in GitHub Desktop.
Save M3ales/d8608fc639c706d60bc953c6ee7e3da8 to your computer and use it in GitHub Desktop.
RxJs Angular Destroyed Unsubscribed OnDestroy

RxJs Unsubscribe

Given:

export class Example implements OnDestroy {
    isLoading : boolean;
    isSaving : boolean;
    isUndoing : boolean;
    isStarting : boolean;
    constructor(service : Service){
        this.service.isLoading$.subscribe(next => this.isLoading = next)
        this.service.isSaving$.subscribe(next => this.isSaving = next);
        this.service.isUndoing$.subscribe(next => this.isUndoing = next);
        this.service.isStarting$.subscribe(next => this.isStarting = next);
    }
    ngOnDestroy() {
        this.service.isLoading.unsubscribe();
        this.service.isSaving.unsubscribe();
        this.service.isUndoing.unsubscribe();
        this.service.isStarting.unsubscribe();
    }
}

Rather:

export class Example implements OnDestroy {
    isLoading : boolean;
    isSaving : boolean;
    isUndoing : boolean;
    isStarting : boolean;
    destroyed$ : ReplaySubject<boolean> = new ReplaySubject(1);
    constructor(service : Service){
        this.service.isLoading$.pipe(takeUntil(this.destroyed$)).subscribe(next => this.isLoading = next)
        this.service.isSaving$.pipe(takeUntil(this.destroyed$)).subscribe(next => this.isSaving = next);
        this.service.isUndoing$.pipe(takeUntil(this.destroyed$)).subscribe(next => this.isUndoing = next);
        this.service.isStarting$.pipe(takeUntil(this.destroyed$)).subscribe(next => this.isStarting = next);
    }
    ngOnDestroy() {
        this.destroyed$.next(true);
        this.destroyed$.complete();
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment