链接多个RxJS可观测值并赋值



我有属性

currentApplication: IApplicationModel;
logos: IImagesModel[];
backgrounds: IImagesModel[];

我有三个像这样的可观测值:

loadApplication(): Observable<IApplicationModel> {
return this.applicationService.getById(this.applicationId);
}
loadApplicationLogos(): Observable<IImagesModel[]> {
return this.applicationService.getApplicationFiles(this.applicationId, "logo");
}
loadApplicationOldBackgrounds(): Observable<IImagesModel[]> {
return this.applicationService.getApplicationFiles(this.applicationId, "background");
}

并且它们不相互依赖。我希望有一个订阅,例如使用mergeMap((,但我也希望分配每个可观察的结果。

this.loadApplication()
.pipe(
mergeMap(application => this.loadApplicationLogos()),
mergeMap(application => this.loadApplicationOldBackgrounds()),

)
.subscribe(res => {

})

如何将应用程序和徽标分配给当前应用程序和标识?我应该在每次mergeMap((之前使用tap((吗?还是有更好的方法来处理与mergeMap不同的东西?

您可以使用combineLatest同时进行所有调用,并在最后合并结果:

combineLatest([
this.loadApplication(),
this.loadApplicationLogos(),
this.loadApplicationOldBackgrounds()
]).pipe(
map(([currentApplication, logos, backgrounds]) => {
return {
currentApplication,
logos,
backgrounds
};
})
).subscribe(res => console.log(res));

当所有可观测者都至少发射一次时,它就会发射。

适合您的完美解决方案是使用combineLatest运算符

combineLatest([
loadApplication(),
loadApplicationLogos(),
loadApplicationOldBackgrounds(),
]).subscribe(([res1,res2,res3]) => {...})

将要发生的事情是,一旦你的三个可观察器都返回了一些东西,你将进入subscribe,并将接收数组中的所有数据,之后你可以用任何你喜欢的方式处理数据。

如果您需要并行加载这三个,您可以使用combineLatest,正如其他人所提到的那样。如果你需要先加载应用程序,你可以使用这样的东西来处理它:

this.loadApplication().pipe(
switchMap((application) => {
return combineLatest(
this.loadApplicationLogos(application),
this.loadApplicationOldBackgrounds(application)
).pipe(([logos, backgrounds]) => {
// create an updated application object with logos and backgrounds...
return {...application, appLogs: logos, appBackgrounds: backgrounds};
});
})
);

这里有一个我在学习RxJS时发现非常有用的工具:http://reactivex.io/rxjs/manual/overview.html#choose-操作员

如果您有复杂的状态管理需求,并且使用了大量RxJS,我建议您查看NgRedux:

https://ngrx.io/docs

坦率地说,这一切都取决于你的经验。如果使用combineLatest运算符,则每当某些输入流产生值时,该流就会产生一个新值。此外,combineLatest在序列中运行可观测性

可能,您想看看并行运行可观测值的forkJoin运算符。它等待所有可观察器产生它们的第一个值并完成它自己。

forkJoin([loadApplication(),loadApplicationLogos(), loadApplicationOldBackgrounds()]).subscribe(([res1,res2,res3]) => {...})

最新更新