Reputation: 1874
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.
Upvotes: 7
Views: 6298
Reputation: 7410
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 usedUpvotes: 5
Reputation: 13471
You can also use compose which will get an observable and will return a different.
Observable.Transformer<Integer, String> transformIntegerToString() {
return observable -> observable.map(String::valueOf);
}
@Test
public void observableWithTransformToString() {
Observable.from(Arrays.asList(1,2,3))
.map(number -> {
System.out.println("Item is Integer:" + Integer.class.isInstance(number));
return number;
})
.compose(transformIntegerToString())
.subscribe(number -> System.out.println("Item is String:" + (String.class.isInstance(number))));
}
You can see more examples here
https://github.com/politrons/reactive
Upvotes: 0
Reputation: 1960
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]
Upvotes: 5