racing
Creates a racing scope that allows multiple coroutine blocks to race against each other. The first block to complete successfully will provide the result, and all other blocks will be cancelled.
This function provides structured concurrency guarantees - all racing blocks will be properly cancelled when the racing scope completes, either normally or exceptionally.
Example:
import arrow.fx.coroutines.racing
import kotlinx.coroutines.delay
import kotlin.time.Duration.Companion.milliseconds
suspend fun main() {
val result = racing<String> {
// This block will be cancelled when the timeout completes
race {
delay(1000)
"Slow result"
}
// This block will complete first and provide the result
onTimeout(time = 100.milliseconds) {
"Timeout result"
}
}
println(result) // Prints: Timeout result
}Content copied to clipboard
Return
The result of the first racing block to complete successfully.
Parameters
A
The type of value that will be returned by the racing blocks.
block
The block of code to execute within the racing scope.