RXJS等待数组中的所有可观察值完成(或错误) [英] RXJS Wait for all observables in an array to complete (or error)

查看:66
本文介绍了RXJS等待数组中的所有可观察值完成(或错误)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将可观察对象推入类似这样的数组中...

I'm pushing observables into an array like such...

var tasks$ = [];
tasks$.push(Observable.timer(1000));
tasks$.push(Observable.timer(3000));
tasks$.push(Observable.timer(10000));

我想要一个Observable在所有任务$完成后发出.请记住,实际上,tasks $没有已知数量的Observable.

I want an Observable that emits when all tasks$ have completed. Keep in mind, in practice, tasks$ doesn't have a known number of Observables.

我尝试了Observable.zip(tasks$).subscribe(),但是如果只有1个任务,这似乎失败了,这使我相信ZIP需要偶数个元素才能按照我期望的方式工作.

I've tried Observable.zip(tasks$).subscribe() but this seems to fail in the event that there is only 1 task, and is leading me to believe that ZIP requires an even number of elements in order to work the way I would expect.

我已经尝试过Observable.concat(tasks$).subscribe(),但是concat运算符的结果似乎只是一个可观察对象的数组...例如与输入基本相同.您甚至都无法致电订阅.

I've tried Observable.concat(tasks$).subscribe() but the result of the concat operator just seems to be an array of observables... e.g. basically the same as the input. You can't even call subscribe on it.

在C#中,这类似于Task.WhenAll().在ES6中,保证类似于Promise.all().

In C# this would be akin to Task.WhenAll(). In ES6 promise it would be akin to Promise.all().

我遇到了许多SO问题,但是它们似乎都在等待已知数量的流(例如将它们映射在一起).

I've come across a number of SO questions but they all seem to deal with waiting on a known number of streams (e.g. mapping them together).

推荐答案

如果您想编写一个在所有源可观测对象完成时发出的可观测对象,则可以使用

If you want to compose an observable that emits when all of the source observables complete, you can use forkJoin:

import { Observable } from 'rxjs/Observable';
import 'rxjs/add/observable/forkJoin';
import 'rxjs/add/operator/first';

var tasks$ = [];
tasks$.push(Observable.timer(1000).first());
tasks$.push(Observable.timer(3000).first());
tasks$.push(Observable.timer(10000).first());
Observable.forkJoin(...tasks$).subscribe(results => { console.log(results); });

这篇关于RXJS等待数组中的所有可观察值完成(或错误)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆