The group_by operator

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:

Figure 9.3: The group_by 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:

on_next obs <0x105f70048>: 1
on_next obs <0x105ee6b70>: 2
on_next obs <0x105f70048>: 3
on_next obs <0x105ee6b70>: 4
on_next obs <0x105f70048>: 5
on_next obs <0x105ee6b70>: 6
on_completed

Even and odd items are received interleaved, on two different observables. One observable contains all the even numbers, and the other all the odd numbers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.141.28.107