xsnippet logotype

xsnippet

#363493, Untitled [ Text only ]

by Guest
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import { OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

export abstract class UnsubscribableComponent implements OnDestroy {

    public set loading(value: boolean) {
        this._loading = value;
    }

    public get loading(): boolean {
        return this._loading;
    }

    /**
     * Please, look there for more information
     * https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87
     *
     * Such proposal is more recommended, but for 2-way compability,
     * the approach with subscribers has been left.
     *
     * Approach using isAlive property can be achieved by using the
     * rxjs#takeWhile(() => this.isAlive);
     */
    public isAlive: boolean = true;

    protected subscribers: Array<Subscription> = [];

    private _loading: boolean = false;

    public ngOnDestroy(): void {
        this.isAlive = false;
        this.clearSubscriptions();
    }

    protected clearSubscriptions(): void {
        for (const subscription of this.subscribers) {
            if (subscription && !subscription.closed) {
                subscription.unsubscribe();
            }
        }
        this.subscribers.length = 0;
    }
}