suspendCoroutineWithTimeout

inline suspend fun <T> suspendCoroutineWithTimeout(timeout: Duration, crossinline block: (Continuation<T>) -> Unit): T

Suspends the current coroutine with a timeout, useful for operations that need time-based cancellation.

This function combines suspendCancellableCoroutine with withTimeout to create a coroutine suspension point that automatically cancels if not resumed within the specified duration.

Usage Example

suspend fun waitForBluetoothConnection(): BluetoothDevice {
return suspendCoroutineWithTimeout(30.seconds) { continuation ->
bluetoothManager.connect { device ->
continuation.resume(device)
}
}
}

Return

The result provided to the continuation's resume function.

Parameters

T

The type of the result value.

timeout

The maximum duration to wait before throwing kotlinx.coroutines.TimeoutCancellationException.

block

Lambda that receives a Continuation to resume with the result.

Throws

TimeoutCancellationException

if the timeout is reached.


inline suspend fun <T> suspendCoroutineWithTimeout(timeMillis: Long, crossinline block: (CancellableContinuation<T>) -> Unit): T

Suspends the current coroutine with a timeout in milliseconds, useful for operations that need time-based cancellation.

This function combines suspendCancellableCoroutine with withTimeout to create a coroutine suspension point that automatically cancels if not resumed within the specified time.

Usage Example

suspend fun waitForSensorData(): SensorData {
return suspendCoroutineWithTimeout(5000L) { continuation ->
sensorManager.requestData { data ->
continuation.resume(data)
}
}
}

Return

The result provided to the continuation's resume function.

Parameters

T

The type of the result value.

timeMillis

The maximum time in milliseconds to wait before throwing kotlinx.coroutines.TimeoutCancellationException.

block

Lambda that receives a CancellableContinuation to resume with the result.

Throws

TimeoutCancellationException

if the timeout is reached.