Composing single parameter functions with lists
Sometimes, you may have a list of elements and you need to apply an async function that takes only a single parameter. In a real case scenario, it could be a function that inserts a single entity in your database. For our simplified scenario, let’s assume it’s this function:
static Observable addTwo(number) {
Observable.just(number + 2)
}
And we want to apply this function to our list of numbers [1, 2, 3].
In this case, we can use the Observable.from(list) (docs here) to generate a list of observables containing each list element and then using reduce to get our list back.
static Observable addTwoOb(numbers) {
Observable.from(numbers)
.flatMap {
addTwo(it)
}
.reduce([]) { acc, elem ->
acc << elem
acc
}
}
Here, [] is the initial value for our accumulator, which is returned in the callback function.
The source code for this project is here. See ya!