I have the following code which works as expected. However, I do not like having a blockingGet. Is there a way to move the getSingle() call higher up into a 'global' variable of the Observable to avoid this? In other words I'd like getSingle to complete without using blockingGet before moving on in the code. Note that in the map call I need access to the foos, bar and getSingle() response.
Any help would be appreciated!
public List<Baz> example(Single<Collection<Foo>> foosSingle, Collection<Bar> bars) {
return foosSingle
.flatMap(foos ->
Observable.fromIterable(bars)
.map(bar -> getBaz(foos, getSingle(bar.getBlah()).blockingGet(), bar.getFlaz())
.toList()
);
}
FWIW I tried replacing the .map call with something like this:
.map(bar -> Lists.ArrayList(bar, getSingle(bar.getBlah()).blockingGet())
.map(list -> getBaz(foos, list.get(1), list.get(0).getFlaz())
which gives me access to all variables I need, but it doesn't resolve the blockingGet issue.
Use .flatMap
instead of map
public List<Baz> example(Single<Collection<Foo>> foosSingle, final Collection<Bar> bars) {
return foosSingle
.flatMap(foos ->
Observable.fromIterable(bars)
.flatMapSingle(bar -> {
return getSingle(bar.getBlah())
.map(x -> getBaz(foos, x, bar.getFlaz()))
})
.toList()
);
}