...

/

Setting Timeouts, Dispatchers and Structured Concurrency

Setting Timeouts, Dispatchers and Structured Concurrency

Learn about setting timeouts, dispatchers and structured concurrency in Kotlin.

Setting timeouts

Let’s consider the following situation. What if, as happens in some cases, fetching the user’s profile takes too long? What if we decided that if the profile takes more than 0.5 seconds to return, we’ll just show no profile?

This can be achieved using the withTimeout() function:

val coroutine = async {
withTimeout(500) {
try {
val time = Random.nextLong(1000)
println("It will take me $time to do")
delay(time)
println("Returning profile")
"Profile"
}
catch (e: TimeoutCancellationException) {
e.printStackTrace()
}
}
}
Creating a timeout with async

We set the timeout to be 500 milliseconds, and our coroutine will delay for between 0 and 1000 milliseconds, giving it a 50 percent chance of failing.

We’ll await the results from the coroutine and see what happens:

val result = try {
coroutine.await()
}
catch (e: TimeoutCancellationException) {
"No Profile"
}
println(result)
Handling timeout with await

Here, we benefit from the fact that try is an expression in Kotlin. So, we can return a result immediately from it.

If the coroutine manages to return ...