Flatmap and friends
In the previous section, we learned how to transform and combine observables with operations such as map, reduce, and zip
. However, the two observables above—musicians and bands—were perfectly capable of producing values on their own. They did not need any extra input.
In this section, we examine a different scenario: we'll learn how we can combine observables, where the output of one is the input of another. We encountered flatmap
before in Chapter 1, What is Reactive Programming? If you have been wondering what its role is, this section addresses exactly that.
Here's what we are going to do: given an observable representing a list of all positive integers, we'll calculate the factorial for all even numbers in that list. Since the list is too big, we'll take five items from it. The end result should be the factorials of 0, 2, 4, 6, and 8, respectively.
The first thing we need is a function to calculate the factorial of a number n, as well...