试图延迟API调用,直到使用RXJS完成批处理调用



我有一个大的事件列表,其中有一个与它们相关的附加信息,这需要计算,并且总体上是相当繁重的后端进程。因此,我首先填充事件并以批处理的方式获取附加数据。我试着先看看批,看看,如果相关的数据在那里,如果没有,我将根据需要获取它。我试图通过使用一个行为主题(linksReady)来跟踪我何时获取批处理以及何时完成来避免这种情况。

getLinksFromApi() {
this.linksReady.next(false);
this.api.getBatchData(searchdefinitions).subscribe(res => {
this.Links = res;
this.linksReady.next(true);
});}

然后,当这个准备好了,我搜索这个数组:

getLinkForEventDirect(id:number):Observable<RegisterLinksDto> {
let temp = this.Links.find(x => x.id === id);
if (temp == null) {
return this.api.getLinkById(id);
} else {
return of(temp);
}

只要我将所有使用getLinkForEventDirect作为源的异步管道与linksReady的可观察对象包围起来,就可以正常工作,但这很麻烦,感觉相当笨拙。我想做的是遵循

getLinkForEvent(id:number):Observable<RegisterLinksDto> {
return this.linksReady$.pipe(
switchMap((x) => {
if (x === true){
return this.getLinkForEventDirect(id);
} else {
return EMPTY;
}
},
));
}

在我的测试中,它似乎与包装的async-pipes具有相同的效果。

问题:

  1. 是否有更好的方法用RXJS做到这一点?
  2. 我可以让getLinkForEventDirect更简单吗?
  3. 在这种情况下,EMPTY是否正确返回可观察对象?

可以这样写:

创建一个可观察对象,通过shareereplay来兑现一个值。立即启动可观察对象(这样它就能尽快兑现)。然后使用这个可观察对象在以后返回一个链接。

batchData$: Observable<RegisterLinksDto[]>;
constructor(){
this.batchData$ = this.api.getBatchData(searchdefinitions).pipe(shareReplay(1));
this.batchData$.pipe(take(1)).subscribe();
}
getLinkForEventDirect(id:number): Observable<RegisterLinksDto> {
return this.batchData$.pipe(
take(1),
switchMap(links => {
const temp = links.find(x => x.id === id);
if (temp == null) {
return this.api.getLinkById(id);
} else {
return of(temp);
}
)
);
}

最新更新