Fan-In
The objective of the Fan-In design pattern is to consolidate results generated by multiple workers. This pattern becomes invaluable when workers produce results that need to be gathered and managed.
Unlike the Fan-Out design pattern we discussed earlier, which involves multiple coroutines reading from the same channel, Fan-In reverses the roles. In this pattern, multiple coroutines can contribute their results by writing them to the same shared channel.
Combining the Fan-Out and Fan-In design patterns lays a solid foundation for building MapReduce
algorithms. To illustrate this concept, we’ll make a slight modification to the workers used in the previous example:
private fun CoroutineScope.doWorkAsync(
channel: ReceiveChannel<String>,
resultChannel: Channel<String>
) = async(Dispatchers.Default) {
for (p in channel) {
resultChannel.send(p.repeat(2))
}
}
Now, each worker sends the results of its computations to a common...