Within my service, I use an Observable to load data in the constructor. Later on, this data can be accessed using a getter, which should either return the data immediately if it's available or wait until the loading process is complete. Here is an example of how I implemented this in TypeScript:
class DataLoadingService {
private onDataLoaded = new Subject<any>();
private loaded = false;
private data: any;
constructor(
private dataProvider: DataProvider
) {
this.dataProvider.loadData().subscribe(data => {
this.data = data;
this.loaded = true;
this.onDataLoaded.next(null);
});
}
public fetchDataOrWait(): Observable<any> {
if (this.loaded) {
return of(this.data);
}
return new Observable((observer: Observer<any>) => {
const subscription = this.onDataLoaded.subscribe(() => {
observer.next(this.data);
observer.complete();
subscription.unsubscribe();
});
});
}
}
I'm wondering if there is a more straightforward way to achieve this functionality, as it seems like a common pattern.
Additionally, I am concerned about a possible race condition when the loading process completes while the execution is between lines marked A and B (although I'm unsure if threads are involved here, as the data is loaded asynchronously).