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.
3 Answers
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]
Comments
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:
- The number of
Listsemitted by theObservableis maintained. i.e. if the source emits 3 lists, there will be 3 transformed lists on the other end - Using
Observable.fromIterable()will ensure the innerObservableterminates so thattoList()can be used
Comments
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