ru.hnau.jutils.coroutines.deferred.DeferredTimeoutExtensions.kt Maven / Gradle / Ivy
package ru.hnau.jutils.coroutines.deferred
import kotlinx.coroutines.Deferred
import kotlinx.coroutines.TimeoutCancellationException
import ru.hnau.jutils.TimeValue
import ru.hnau.jutils.coroutines.withTimeout
suspend fun Deferred.awaitWithTimeout(
time: TimeValue,
converter: suspend (T) -> R,
timeoutAction: suspend (TimeoutCancellationException) -> R = { throw it }
) =
try {
withTimeout(time) { converter.invoke(await()) }
} catch (ex: TimeoutCancellationException) {
cancel()
timeoutAction.invoke(ex)
}
suspend fun Deferred.awaitWithTimeout(
time: TimeValue,
timeoutAction: suspend (TimeoutCancellationException) -> T = { throw it }
) = awaitWithTimeout(
time = time,
converter = { it },
timeoutAction = timeoutAction
)