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

Suppose I have an observable Observable<List<A>> and I want to convert it to Observable as Observable<List<B>> . Is there a better way to convert List<A> to List<B> . A similar implementation of the Javascript map would be ideal.

+6
source share
3 answers

You can use Observable.from(Iterable<A>) to get an Observable<A> , display it (A => B) and convert to List<B> using Observable.toList()

 Observable.from(Arrays.asList(1, 2, 3)) .map(val -> mapIntToString(val)).toList() 

eg.

  Observable.from(Arrays.asList(1, 2, 3)) .map(val -> val + "mapped").toList() .toBlocking().subscribe(System.out::println); 

gives

[1mapped, 2mapped, 3mapped]

+4
source

I answered another similar question: fooobar.com/questions/195966 / ...

I copied the answer here for convenience (not sure if this is against the rules):

If you want to keep the Lists emitted by the Observable source, but convert the contents, i.e. Observable<List<SourceObject>> in 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 provides a couple of things:

  • The number of Lists emitted by the Observable . those. if the source emits 3 lists, the other end will have 3 converted lists.
  • Using Observable.fromIterable() ensures that the internal Observable completes so that toList() can be used
+2
source

You can also use compose , which will get visible and return another.

 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

0
source

All Articles