等待多个异步调用在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.