Collecting emissions of grouped observables into one list

I have the following usage example (this, of course, is a far-fetched example, but as soon as I know the answer, I can transfer it to the real problem that I have to solve):

  • Get a list of integers.
  • Group them by operation% 4
  • Collect the elements of each group into lists
  • Ignore any groups / lists that have fewer items than 3 items
  • Select one list whose elements are the lists created in step # 3

Here is my current code:

Observable .from(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12)) .groupBy(item -> item % 4) .subscribe(groupedObservable -> { groupedObservable .toList() .filter(list -> list.size() > 2) .subscribe(result -> { System.out.printf("%d results %s%n", result.size(), result); }); }); 

and its output:

 4 results [0, 4, 8, 12] 3 results [2, 6, 10] 3 results [3, 7, 11] 

Thus, it prints how many elements each group has, and then a list of elements. I would like the result to be (I don't really care about the keys):

3 results: [[0, 4, 8, 12], [2, 6, 10], [3, 7, 11]]

i.e. somehow smooth the grouped observables into a single list. I do not do this. For example, adding .flatMap(integers -> Observable.just(integers)) after filter does not change anything, since it affects only each grouped observable, and not the entire stream. Is there a way to fulfill my requirements?

+7
rx-java
source share
1 answer

I'm not sure if I understood you correctly, but based on the desired result, here is the code that you can search for:

 public static void main(final String[] args) throws Exception { Observable.from(Arrays.asList(0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 12)) .groupBy(item -> item % 4) .flatMap(Observable::toList) .filter(integers -> integers.size() > 2) .toList() .subscribe(result -> { System.out.printf("%d results %s%n", result.size(), result); }); } 
+16
source share

All Articles