Racing
Racing is a design pattern that runs multiple jobs concurrently, picking the result that returns first as the winner and discarding others as losers.
We can implement Racing in Kotlin using the select()
function on channels.
Let's imagine you are building a weather application. For redundancy, you fetch the weather from two different sources, Precise Weather and Weather Today. We'll describe them as two producers that return their name and temperature.
If we have more than one producer, we can subscribe to their channels and take the first result that is available.
First, let's declare the two weather producers:
fun CoroutineScope.preciseWeather() = produce { delay(Random.nextLong(100)) send("Precise Weather" to "+25c") } fun CoroutineScope.weatherToday() = produce { delay(Random.nextLong(100)) send("Weather Today" to ...