Is withTimeout() a coroutine builder? Does it block the calling thread?

  1. 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?

  2. 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

What more information in addition to posted in StackOverflow do you need? withTimeout() is just one of many functions that execute a block of code in some kind of a sub-context and do it synchronously in relation to the caller. Other examples are coroutineScope(), supervisorScope(), withContext(), withLock(), withPermit(), select() and if we count similar functions not related specifically to coroutines then there are probably tens of them in the stdlib.

All these functions inherit the coroutine context from the caller and usually accept context elements as their params to merge them with the parent context.

BTW, running myScope.launch() inside runBlocking() in your example doesn’t make too much sense. They could/should be executed outside of runBlocking(), with the same effect.