Search code examples
angularionic3observableobserver-pattern

Proper Observable Management


I'm working on an Ionic 3 / Angular app. I came across some code in the enterprise project's Data Store Abstract Class. The refresh function in the store creates a const cachedObs. I'm not very familiar with observables and my question is, if the refresh function is called several times, is this function creating multiple observables in the background instead of reusing one observable? The developer of this code is unsure as well. We have not run into any performance issues yet, but I want to ensure this code isn't leaky.

These observables are not unsubscribed from as they update critical data in the app. Any help with this is appreciated.

public refresh(): Observable<T> {
    const cachedObs = Observable.fromPromise(this._storage.get(this._key).catch(() => this._initialState));
    cachedObs.subscribe(data => this.set(data ? JSON.parse(data) as T : this._initialState));
    return cachedObs;
};

Solution

  • So, you are definitely creating a new observable each time and not reusing the same stream. On the plus side, in this scenario, its not really a problem. If an observable completes, then it automatically unsubscribes all subscriptions.

    fromPromise is an observable creation mechanism that will only emit one value, that complete itself. So there is no need to unsubscribe.

    You can prove this by in the subscribe() method. It has 3 arugments, the first is the success, then the fail, and then the complete. So you could do .subscribe(null, null, () => console.log("Complete")). If you see the complete fire, you know you dont need to worry about leaks!