[英]RxJS - when does forkJoin trigger?
What would cause individual subscribe
to trigger, but forkJoin
to not trigger? 什么会导致个人
subscribe
触发,而forkJoin
不触发?
I've sent off a request which triggers subject.subscribe
, but when I've added it to an array to use with forkJoin, the forkJoin().subscribe
doesn't run. 我已经发出了触发
subject.subscribe
的请求,但是当我将其添加到要与forkJoin一起使用的数组中时, forkJoin().subscribe
不会运行。 The result that comes back is an object. 返回的结果是一个对象。
let responses$ = [];
_.map(items, (item) => {
let subject = new Subject();
this.apiService.postRequest("/api/my-endpoint", data).subscribe(subject);
responses$.push(subject);
subject.subscribe((res) => { console.log("this triggers") });
});
Observable.forkJoin(responses$).subscribe((res) => {
console.log("this does not trigger");
});
And here is postRequest - I'm not sure I'm doing it right, I wanted to chain it like promises. 这是postRequest-我不确定我做对了吗,我想像promise一样链接它。
public postRequest(url: string, data: any) {
return this.getToken().flatMap((accessToken: Response) => {
return this.post(url, data, {'Authorization': 'Bearer ' + accessToken});
});
}
Frankly I just wanted to do something similar to $q.all
with promises. 坦白说,我只是想做类似的东西
$q.all
与承诺。
forkJoin
will emit an array containing the last values from each of the observables passed to it. forkJoin
将发出一个数组,其中包含传递给它的每个可观察对象的最后一个值。 It emits the array when all of the observables have completed. 当所有可观测值都完成时,它将发出数组。
So each observable passed to it will need to emit at least one value and will also need to complete. 因此,传递给它的每个可观察对象将需要发出至少一个值,并且还需要完成。
The reason your subscription to the joined observable does not trigger is most likely because the observables are not completing. 您对已加入的可观察对象的订阅未触发的原因很可能是由于可观察对象尚未完成。 You've not included the implementation of
getToken()
in the question, but unless that observable completes, forkJoin
will neither emit a value nor complete. 您没有在问题中包含
getToken()
的实现,但是除非该可观察的操作完成,否则forkJoin
既不会发出值也不会完成。
You could ensure that the observables complete by using first()
in the postRequest
implementation: 您可以通过在
postRequest
实现中使用first()
来确保可观察对象完成:
public postRequest(url: string, data: any) {
return this.getToken()
.first()
.flatMap((accessToken: Response) => {
return this.post(url, data, {'Authorization': 'Bearer ' + accessToken});
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.