Search code examples
rx-javarx-java3

Use flatmap with grouped observables


I am new in RxJava and trying to understand it. I have the following source:

Observable<Employee> obs = Observable.just(
    new Employee(101, "Jim", 68_000, 4.2),
    new Employee(123, "Bill", 194_000, 6.7));  

obs.groupBy(e -> e.getRating())
                .flatMap(e-> {
                    return Observable.fromIterable(
                        Arrays.asList(e.getKey())
                    );
                })
                .subscribe(System.out::println);
 

This prints the key which is the ratings but I can't print the values.
Is it possible using flatMap?


Solution

  • groupBy returns an Observable that emits a GroupedObservable for each unique key. A GroupedObservable is really just an Observable with the addition of the getKey method, so you can identify which key that GroupedObservable is associated with. So, if you want to emit each value in each GroupedObservable, just pass the whole thing directly to the flatMap call:

    Observable<Employee> obs = Observable.just(
        new Employee(101, "Jim", 68_000, 4.2),
        new Employee(123, "Bill", 194_000, 6.7));  
    
    obs.groupBy(e -> e.getRating())
        .flatMap(e -> e)
        .subscribe(System.out::println);