https://kotlinlang.org logo
#coroutines
Title
# coroutines
s

SrSouza

05/01/2020, 9:50 PM
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

octylFractal

05/01/2020, 9:56 PM
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

SrSouza

05/01/2020, 9:59 PM
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

elizarov

05/01/2020, 10:01 PM
withContext
suspends until all the coroutines launched in its scope complete.
👍 1
s

SrSouza

05/01/2020, 10:27 PM
Good to know that, tkx Roman.
e

EyeCon

05/02/2020, 5:27 PM
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

octylFractal

05/02/2020, 5:29 PM
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

EyeCon

05/02/2020, 8:57 PM
Thanks a lot!
2 Views