S Haque
S Haque

Reputation: 7271

Convert Observable<List<String>> into Observable<List<Integer>> with RxJava mapping

I have a function getColorList which returns an ArrayList of String type

private static List<String> getColorList() {
        ArrayList<String> colors = new ArrayList<>();
        colors.add("red");
        colors.add("green");
        colors.add("blue");
        colors.add("pink");
        colors.add("brown");
        return colors;
}

I want to get a Observable<List<Integer>> from that string ArrayList where the list is the lengths of those strings.

Observable<List<Integer>> listLengthObservable = Observable.fromArray(getColorList()).map( //Mapping function );

What would be the mapping function for this conversion.

Upvotes: 0

Views: 1612

Answers (1)

yosriz
yosriz

Reputation: 10267

You can flatten the list, map each string to each length, and then collect it back to list.

Single<List<Integer>> listLengthObservable = Observable.fromIterable(getColorList())
            .map(s -> s.length())
            .toList();

More elegant method is to use reduceWith:

Single<List<Integer>> listLengthObservable = Observable.fromIterable(getColorList())
            .reduceWith(() -> new ArrayList<Integer>(), (integers, s) -> {
                integers.add(s.length());
                return integers;
            });

which goes over all the items in the Observable and collect them with the input integers list you provide.

Both operators return Single (as there is by definition single emission), you can easily convert it to Observable using toObservable() if you must need it.

Upvotes: 4

Related Questions