Lets say I have an observable
Observable<List<A>>
and I want to convert it to an Observable as Observable<List<B>>
. Is there any best possible way to convert List<A>
into List<B>
. Javascript's map
's like implementation would be the ideal situation.
You can use Observable.from(Iterable<A>)
to get Observable<A>
, map it (A => B), and convert to List<B>
with Observable.toList()
Observable.from(Arrays.asList(1, 2, 3))
.map(val -> mapIntToString(val)).toList()
E.g.
Observable.from(Arrays.asList(1, 2, 3))
.map(val -> val + "mapped").toList()
.toBlocking().subscribe(System.out::println);
yields
[1mapped, 2mapped, 3mapped]
I answered another similar question here: https://stackoverflow.com/a/42055221/454449
I've copied the answer here for convenience (not sure if that goes against the rules):
If you want to maintain the Lists
emitted by the source Observable
but convert the contents, i.e. Observable<List<SourceObject>>
to Observable<List<ResultsObject>>
, you can do something like this:
Observable<List<SourceObject>> source = ...
source.flatMap(list ->
Observable.fromIterable(list)
.map(item -> new ResultsObject(item))
.toList()
.toObservable() // Required for RxJava 2.x
)
.subscribe(resultsList -> ...);
This ensures a couple of things:
Lists
emitted by the Observable
is maintained. i.e. if the source emits 3 lists, there will be 3 transformed lists on the other endObservable.fromIterable()
will ensure the inner Observable
terminates so that toList()
can be usedIf you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With