June 2018
Intermediate to advanced
310 pages
6h 32m
English
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, TimeUnit.MILLISECONDS) { try { val time = Random().nextInt(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 1,000 milliseconds, giving it a 50 percent chance to fail.
We'll await results from the coroutine and see what happens:
val result = Read now
Unlock full access