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. A block is by default considered successful if it doesn't throw an exception nor raises an error through arrow.core.raise.Raise. To change this behavior, provide a success condition to race or use raceOrFail.
This function provides structured concurrency guarantees - all racing blocks will be properly cancelled when the racing scope completes, either normally or exceptionally.
Example 1:
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
}Example 2:
import arrow.fx.coroutines.racing
import arrow.core.raise.either
suspend fun main() {
val result = either<String, Int> {
racing<Int> {
race { delay(1000) ; 104 }
// this blocks ends earlier,
// but it is not considered successful
race { raise("a problem") }
}
}
println(result) // Prints: Either.Right(104)
}Return
The result of the first racing block to complete successfully.
Parameters
The type of value that will be returned by the racing blocks.
The block of code to execute within the racing scope.