等待多个异步调用在RxJava中完成 [英] Wait for multiple async calls to finish in RxJava

查看:155
本文介绍了等待多个异步调用在RxJava中完成的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的情况很简单,但是我似乎无法在任何地方找到它.

My scenario is quite simple, but I don't seem to able to find it anywhere.

我有一组要迭代的元素,每个元素调用一个异步函数,然后等待所有元素完成(这又以异步方式发生,以函数的逻辑实现).我对RxJava相对较新,过去曾在NodeJS中通过将回调传递给函数并在最后等待而轻松地做到这一点.这是我需要的伪代码(元素的迭代器不需要是同步的也不是有序的):

I have a set of elements that I want to iterate through, for each one call an async function, and then wait for all of them to finish (which again happens in an asynchronous fashion, implemented in the logic of the function). I'm relatively new to RxJava and used to do this easily in NodeJS by passing callback to the function and wait at the end. Here's the pseudocode of what I need (the iterator for elements does not need to be synchronous nor ordered):

for(line in lines){
 callAsyncFunction(line);
}
WAIT FOR ALL OF THEM TO FINISH

非常感谢您的帮助!

推荐答案

使用Rx:

Observable
.from(lines)
.flatMap(line -> callAsyncFunctionThatReturnsObservable(line).subscribeOn(Schedulers.io())
.ignoreElements();

这时,根据您要执行的操作,可以使用 .switchIfEmpty(...)订阅另一个可观察对象.

At this point, depending on what you want to do you can use an .switchIfEmpty(...) to subscribe to another observable.

这篇关于等待多个异步调用在RxJava中完成的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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