Hi folks, I'm using `newSingleThreadExecutor` as a...
# coroutines
s
Hi folks, I'm using
newSingleThreadExecutor
as a Dispatcher but I have a problem with it, when I use
delay(x)
, other functions that use the same dispatcher does not execute until the delay finish. Why this is happening if
delay
does not block the Thread.
o
can't reproduce, can you show code?
Copy code
fun main() {
    val dispatcher = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
    runBlocking(dispatcher) {
        launch {
            println("Foo!")
            delay(1000L)
            println("After Foo!")
        }
        launch {
            println("Bar!")
            delay(1000L)
            println("After Bar!")
        }
    }
}
produced:
Copy code
Foo!
Bar!
After Foo!
After Bar!
s
I fix it. The problem was that I have something like this:
Copy code
withContext(singleThread) {
   coroutineScope.launch(singleThread) {
      delay(x)
   }
}
When I migrate it to a function thar produce a Job, fix the problem, But why ?
e
withContext
suspends until all the coroutines launched in its scope complete.
👍 1
s
Good to know that, tkx Roman.
e
Just for may understanding:
coroutineScope {}
also does that, right? So it is only
async
and
launch
that fire off jobs that are executed in parallel, while a scope ending of
coroutineScope
or
withContext
suspends until every child coroutine is completed.
o
yes, that's correct -- though it is incorrect to say only
async
and
launch
start parallel jobs, other things like
produce
,
actor
, and
Flow.launchIn
can also do so -- many methods that take a coroutine scope and aren't suspend will start a separate job
👍 2
e
Thanks a lot!