runInterruptible
suspend fun <T> runInterruptible(context: CoroutineContext = EmptyCoroutineContext, block: () -> T): T
Content copied to clipboard
Calls the specified block with a given coroutine context in a interruptible manner. The blocking code block will be interrupted and this function will throw CancellationException if the coroutine is cancelled.
Example:
withTimeout(500L) { // Cancels coroutine on timeout
runInterruptible { // Throws CancellationException if interrupted
doSomethingBlocking() // Interrupted on coroutines cancellation
}
}
Content copied to clipboard
There is an optional context parameter to this function working just like withContext. It enables single-call conversion of interruptible Java methods into suspending functions. With one call here we are moving the call to Dispatchers.IO and supporting interruption:
suspend fun <T> BlockingQueue<T>.awaitTake(): T =
runInterruptible(Dispatchers.IO) { queue.take() }
Content copied to clipboard
Sources
jvm source
Link copied to clipboard