Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert one type of list to another RXJava? (Javascript map equivalent)

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.

like image 799
Sushant Avatar asked Jun 11 '16 06:06

Sushant


2 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]

like image 166
m.ostroverkhov Avatar answered Oct 06 '22 01:10

m.ostroverkhov


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 Lists emitted by the Observable is 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 inner Observable terminates so that toList() can be used
like image 20
Noel Avatar answered Oct 06 '22 01:10

Noel