I have a service which loads some data in it's constructor with an Observable. Then at some later time the data can be retrieved with a getter. It should return the data right away if it's present. Or wait for loading to finish if that's still in progress. I came up with following example (code is in Typescript):
class MyService {
private loadedEvent = new Subject<any>();
private loaded = false;
private data: any;
constructor(
private dataService: DataService
) {
this.dataService.loadData().subscribe(data => {
this.data = data;
this.loaded = true;
this.loadedEvent.next(null);
});
}
public getDataOrWait(): Observable<any> {
if (this.loaded) { // A
return of(this.data);
}
return new Observable((observer: Observer<any>) => {
const subscription = this.loadedEvent.subscribe(() => { // B
observer.next(this.data);
observer.complete();
subscription.unsubscribe();
});
});
}
}
Is there a simpler way to do this? This must be a common pattern.
Also, I think there is a race condition if loading finishes when execution is somewhere between the lines marked A and B (I am not sure if threads are involved here - the data is loaded async however).