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: