RxJava icon indicating copy to clipboard operation
RxJava copied to clipboard

Recommended way of applying operators to items in sequence of collections?

Open danhawkes opened this issue 11 years ago • 2 comments

When I want to transform the items in collections emitted in a stream, I find myself doing something like this:

Observable<List<Integer>> integerLists = …
// Emits [1, 2, 3], [4, 5, 6]

integerLists.concatMap(list -> Observable.from(list).map(x -> x * 2).toList())
// Emits  [2, 4, 6], [8, 10,12]

Is there are cleaner/recommended way to achieve the same that doesn't require the 'Observable.from … toList' bit?

danhawkes avatar Nov 26 '15 12:11 danhawkes

If you want to avoid in-place mutation, you can use Java Streams which looks almost the same:

Observable<List<Integer>> source = Observable.just(
    Arrays.asList(1, 2, 3), Arrays.asList(4, 5, 6));

source.map(list -> list.stream().map(i -> i * 2).collect(Collectors.toList()))
.subscribe(System.out::println);

So essentially the pattern stays the same.

akarnokd avatar Nov 26 '15 12:11 akarnokd

Right, ok. Thanks for the answer.

danhawkes avatar Nov 26 '15 17:11 danhawkes