The group_by operator groups items of the source observable, where the groups are determined by a selector function. This operator returns a higher-order observable. The following figure shows the marble diagram of this operator:
The prototype of this operator is the following:
group_by(self, key_selector, element_selector=None,
key_serializer=None)
Here, key_selector is a function that returns a key from an item. This key is used to group items per key. The optional element_selector parameter is a function used to map each source item in the observable of the group. Its default value is the identity function (that is, the item is mapped to itself). Finally, the key_serializer optional parameter is a function used to compare whether two keys are equal or not. Its default value is the equality operator.
Here is an example of this operator:
def wrap_items(i):
return i.map(lambda j: 'obs {}: {}'.format(i, j))
numbers = Observable.from_([1, 2, 3, 4, 5, 6])
numbers.group_by(lambda i: i % 2 == 0).flat_map(wrap_items).subscribe(
on_next = lambda i: print("on_next {}".format(i)),
on_error = lambda e: print("on_error: {}".format(e)),
on_completed = lambda: print("on_completed")
)
The key_selector is a function returning True or False depending on whether the item is an even number or an odd one. The items are then flattened before being printed with the name of the observable that carried them. This example gives the following result: