如何使用rxjs返回数据或等待数据加载仍在进行中 [英] How to return data or wait if data loading is still in progress with rxjs
问题描述
我有一个服务,可通过Observable在其构造函数中加载一些数据.然后,在以后的某个时间,可以使用吸气剂来检索数据.如果存在,它将立即返回数据.或者,如果加载仍在进行中,请等待加载完成.我想出了以下示例(代码在Typescript中):
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.
此外,我认为如果执行在标记为A和B的行之间的某处完成,则加载完成会导致竞争(我不确定这里是否涉及线程-但是数据是异步加载的.)
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).
推荐答案
似乎您只是想在逻辑上将数据服务的基于Observable的接口扩展到MyService类的客户端.您可以使用一个新的 AsyncSubject ,它将在所有订阅者身上发出一个单一值已经完成.
It seems that you simply want to logically extend the Observable-based interface of your data service to the clients of your MyService class. You could use a new AsyncSubject, which will emit a single value to all subscribers once it has completed.
class MyService {
private data: any;
private dataSubject = new AsyncSubject<any>();
constructor(
private dataService: DataService
) {
this.dataService.loadData().subscribe(data => {
this.data = data;
this.dataSubject.next(data);
this.dataSubject.complete();
});
}
public getData(): Observable<any> {
return this.dataSubject.asObservable();
}
}
getData
的调用者将执行以下操作:
The caller of getData
would then do something like:
service.getData().subscribe((data) => {
console.log(`got data ${data}`);
});
这篇关于如何使用rxjs返回数据或等待数据加载仍在进行中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!