The fan-in design pattern

It would be great if our coroutines could always make decisions by themselves. But what if they need to return some results from the computation to another coroutine?

The opposite of fan-out is the fan-in design pattern. Instead of multiple coroutines reading from the same channel, multiple coroutines can write their results to the same channel.

Imagine that you're reading news from two prominent tech resources: techBunch and theFerge

Each resource produces the values at its own pace, and sends them over a channel:

private fun techBunch(collector: Channel<String>) = launch {
repeat(10) {
delay(Random().nextInt(1000))
collector.send("Tech Bunch")
}
}

private fun theFerge(collector: Channel<String>) = launch {
repeat(10) {
delay(Random().nextInt(1000))
collector.send("The Ferge")
}
}

By providing them with the same channel, we can combine their results:

val collector = Channel<String>()

techBunch(collector)
theFerge(collector)

runBlocking {
collector.consumeEachIndexed {
println("${it.index} Got news from ${it.value}")
}
}

Combining the fan-out and fan-in design patterns is a good base for Map/Reduce algorithms.

To demonstrate that, we'll generate 10,000,000 random numbers and compute the maximum number among them by dividing this task multiple times.

First, to generate the list of 10,000,000 random integers:

val numbers = List(10_000_000) {
Random().nextInt()
}
..................Content has been hidden....................

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