RxJava Operators: groupBy()

November 14, 2018

groupBy()

With the help of the groupBy() operator, it is possible to group emissions by a given key into seperate Observables.
After the grouping, the returned type is an Observable<GroupedObservable<K,T>> where K is the key and T is the type of the mapped emissions for that given key.

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args)  {
        Observable<String> mySource = Observable.just("a", "bb", "cc", "d", "eee");

        mySource.groupBy(s -> s.length())
                .flatMapSingle(x -> x.toList())
                .subscribe(System.out::println);
    }
}

With the help of flatMap() and reduce(), it is possible to print out the keys and their associated values:

import io.reactivex.Observable;

public class Main {

    public static void main(String[] args)  {
        Observable<String> mySource = Observable.just("a", "bb", "cc", "d", "eee");

        mySource.groupBy(s -> s.length())
                .flatMapSingle(group -> group.reduce("", (x,y) -> "".equals(x) ? y : x + ", " + y)
                                             .map(e -> group.getKey() + ": " + e))
                .subscribe(System.out::println);
    }
}

 

András Döbröntey

About the Author

András Döbröntey

Leave a Comment:

Bitnami