-
There are three main coroutine builders launch, async, runBlocking. My question is about withTimeout() is it a coroutine builder?. if it is, what does it return? what is its scope? what is its dispatcher?
-
I have following piece of code:
val myScope = CoroutineScope(Dispatchers.Default)
runBlocking{
myScope.launch { //coroutine#1
Log.i(TAG, "First coroutine launched")
}
withTimeout(3000){
delay(2000)
Log.i(TAG, "withTimeout block executed")
}
myScope.launch { //coroutine#2
Log.i(TAG, "Second coroutine launched")
}
}
The output is:
First coroutine launched
withTimeout block executed
Second coroutine launched
Here you can see withTimeout takes two seconds to complete the task but still coroutine#2 executed after this block. It means that withTimeout blocks the calling thread. If it does not block the calling thread then output should be like this:
First coroutine launched
Second coroutine launched
withTimeout block executed
Am I right? please help me in understanding this scenario. Thank you
I have also asked this question on stackoverflow
Stackoverflow link