1

I am trying to group several model instances by name and then use take(n) to take only certain items per group, but somehow the take has no effect on GroupedObservable. Here is the code

Let's assume this contains a list with 10 items and 5 have the name "apple" and the other 5 have the name "pear"

Observable<Item> items....

Observable<Item> groupedItems = items.groupBy(Item::name)
.flatMap(it -> it.take(2));

So I imagine groupedItems has to emit 2 "apples" and 2 "pears", but it has all of them instead.

Is there something which I am getting wrong, do I need to do it differently?

X-HuMan
  • 1,488
  • 1
  • 17
  • 37
  • Cancelled groups are recreated when the same key is encountered again. – akarnokd Oct 01 '18 at 14:35
  • @akarnokd could you please comment in a more detailed wat or just give me a hint how to proceed, I am not sure if I understood your comment. – X-HuMan Oct 01 '18 at 15:16

1 Answers1

1

Cancelled groups are recreated when the same key is encountered again. You need to make sure the group is not stopped and you'd have to ignore further items in some fashion:

source.groupBy(func)
.flatMap(group -> 
    group.publish(p -> p.take(5).mergeWith(p.ignoreElements()))
);
akarnokd
  • 69,132
  • 14
  • 157
  • 192