2

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())
   .flatMapSingle(e -> e.toMultimap(key -> e.getKey(), emp -> emp.getName()))
   .subscribe(System.out::println);
 

This approach prints the keys and the associated value.
If I do:

obs.groupBy(e -> e.getRating())
       .flatMapSingle(e -> e.toList())
       .subscribe(System.out::println);   

It seems to print the list of values associated with the key.
But how does flatMapSingle exactly work? What is the difference with flatMap?

Jim
  • 3,845
  • 3
  • 22
  • 47

1 Answers1

1

From the documentation:

Maps each element of the upstream {@code Flowable} into {@link SingleSource}s, subscribes to all of them
     * and merges their {@code onSuccess} values, in no particular order, into a single {@code Flowable} sequence.

It works in the same way in both cases. when your invoke

flatMapSingle(e -> { // convert to some value})

you convert "e" to the value returned by the lambda. in your case "e" is GroupedFlowable.

in first case you convert all the elements to map, which contains entries(key, value), in the second case you convert it to the list. flatMapSingle() method works in the same way in both cases.

You have different results because you use different implementation of Function that you put to flatMapSingle as a parameter.

Function parameter which in you case looks like e -> { .... } determines the way how to handle elements that was emirted by the source.

Anatolii Chub
  • 1,228
  • 1
  • 4
  • 14