Setting Timeouts, Dispatchers and Structured Concurrency
Explore setting timeouts with withTimeout(), using different dispatchers like Default and IO, and applying structured concurrency principles to manage coroutine lifecycles effectively and avoid resource leaks.
We'll cover the following...
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()}}}
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)
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 before the timeout, the value of result ...