我的登录流程具有相当复杂的登录变体,并且必须可扩展以便将来轻松添加更多。因此,最初以典型方式对用户进行身份验证并返回用户对象。然后,我必须进行额外的 http 调用来获取信息,这些信息将在用户被授予访问应用程序的权限之前确定各种要求。这是使用用户对象中返回的一些值来完成的。我想以一种可以轻松添加 http 调用而不更改当前代码的方式编写代码,因此我认为使用 fork join 进行后续调用会很好,因为它们可以并行完成。下面是我的工作代码。
我可以轻松地将新请求添加到 fork join 调用中,虽然它对我来说看起来不太糟糕,但我被告知嵌套订阅是一种代码味道,通常是不好的做法。任何关于如何做得更好的想法都会很棒。
谢谢。
this.authenticate.login(this.model)
.subscribe(
_data => {
this.subscription = Observable.forkJoin(
this.devicesHttp.getDevicesByMacAddress(this.macAddress),
this.teamsService.getTeamsByUserId(_data['userId'])
);
this.subscription.subscribe(
_data => {
// Check login type and other stuff...
}
);
}
);
最佳答案
例如,使用 concatMap()
运算符:
this.authenticate.login(this.model)
.concatMap(_data => Observable.forkJoin(
this.devicesHttp.getDevicesByMacAddress(this.macAddress),
this.teamsService.getTeamsByUserId(_data['userId'])
))
.subscribe(_data => {
// Check login type and other stuff...
});
forkJoin
中的 Observables 将并行运行,forkJoin
将等待它们都完成。
此外,concatMap()
会等待内部 Observable 完成,然后进一步推送结果。
关于javascript - 在另一个可观察值之后使用 fork join 的更好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44309683/