The flat_map operator

The flat_map operator allows us to create an observable from each item emitted on the input observable. Then, each item of the resulting observables is merged in the output observable. The following figure shows how this operator works:

Figure 6.6: The flat_map operator

The prototype of this operator is the following one:

Observable.flat_map(self, selector)

The selector argument is a function called for each input. It takes the item as an input parameter and returns an observable. Here is an example of how to use this operator:

numbers = Observable.from_([1, 2, 3, 4])
numbers.flat_map(lambda i: Observable.from_(range(i, i+2)))
.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")
)

This example gives the following result:

on_next 1
on_next 2
on_next 2
on_next 3
on_next 3
on_next 4
on_next 4
on_next 5
on_completed

For each item of the numbers observable, lambda is called, and it returns two items (the item and another item with its value plus 1). These four dual-item observables are then flattened into a single observable, emitting all their items.

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

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