I have a method that returns a Single<List<Item>>
, and I would like to take each item in this list and pass it downstream to a method that returns Completable
. I want to wait until each item has successfully completed and return a Completable
result. My initial approach was to process each item separately using flatMapIterable
and combine the results using toList
, but I cannot call toList
on a Completable
object. Is there any other way to "aggregate" many Completable
tasks into a single Completable
in this fashion? Here's what I have so far:
public Single<List<Item>> getListOfItems() {
...
}
public Completable doSomething(Item item) {
...
}
public Completable processItems() {
return getListOfItems()
.toObservable()
.flatMapIterable(items -> items)
.flatMapCompletable(item -> doSomething(item))
.toList() // ERROR: No method .toList() for Completable
.ignoreElements();
}
The flatMapCompletable
operator do the trick, you don't need to apply additional operators further.
From the docs:
Maps each element of the upstream Observable into CompletableSources, subscribes to them and waits until the upstream and all CompletableSources complete.
flatMapCompletable
will return Completable
that will complete when all mapped Completables complete their operation:
public Completable processItems() {
return getListOfItems()
.toObservable()
.flatMapIterable(items -> items)
.flatMapCompletable(item -> doSomething(item));
}