Sushant
Sushant

Reputation: 1874

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.

Upvotes: 7

Views: 6298

Answers (3)

Noel
Noel

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:

  • 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

Upvotes: 5

paul
paul

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

m.ostroverkhov
m.ostroverkhov

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

Related Questions