I am stuck on how to convert/transform the following observable type to my target type:
I have observable of type:
Observable<Observable<List<FooBar>>>
I want to convert it to:
Observable<List<FooBar>>
So when I subscribe on it, it emits List<FooBar>
not Observable<List<FooBar>>
I tried with map, flatMap... I could not find a solution.
However, I found a strange looking operator called blockingFirst
which my IDE indicates that it returns Observable<List<FooBar>>
when applied to Observable<Observable<List<FooBar>>>
But the 'blocking' part is confusing me.
I am also looking for better solution than blockingFirst
one, if any.
flatMap
is indeed the way to go:
Observable<Observable<List<FooBar>>> streamOfStreams = ...
Observable<List<FooBar>> listStream =
streamOfStreams.flatMap(listObservable -> listObservable);
I think you should look at it in a different perspective, it is not simple converting from 1 type to another type. Observable
of Observables
means stream that emit streams that each of them emit a list of some items. what you want to achieve is to flatten it to single stream that emit all the lists from all the streams.
flatMap
doing it exactly, you give it an item emission, and return an Observable
, flatMap
will subscribe to the returned Observable
and will merge each item emitted from it to the source stream, in this case, as you simply return each item emission which is Observable<List<FooBar>>
, you practically taking each emitted Observable
, subscribe to it, and merge all its list emissions back, so you get back stream of all the lists from all the Observables
.
blockingFirst
is definitely not the way to go, what it does is to wait (block) until first emission and return this item only, as your items ar Observable<List<FooBar>>
you'll get the only first Observable
. so while it indeed has the same type, its clearly not the same stream you want.