Racing
The Racing design pattern is a concurrency pattern that involves running multiple tasks that produce the same type of data concurrently and selecting the result from the task that completes first, discarding the results from the other tasks.
This pattern is useful in scenarios where you want to maximize responsiveness by accepting the result from the fastest task, even if multiple tasks are competing.
In Kotlin, you can implement the Racing pattern using the select function on channels. Here’s an example using two weather sources, preciseWeather
and weatherToday
, where you fetch weather information from both sources and accept the result from the source that responds first:
runBlocking {
val winner = select<Pair<String, String>> {
preciseWeather().onReceive { preciseWeatherResult ->
preciseWeatherResult
}
weatherToday().onReceive { weatherTodayResult ->
weatherTodayResult
}
...