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

suppoze

11/12/2018, 1:58 PM
Hi all, Is there a Kotlin coroutine implementation equivalent to
Copy code
private val queue = Executors.newSingleThreadExecutor()
//...
    fun submit(data: Data) {
        queue.submit { updateData(data) }
    }
? I was thinking about
Copy code
private val queue = Executors.newSingleThreadExecutor().asCoroutineDispatcher()
// ...
    fun submit(data: Data) = runBlocking {
        launch(queue) {
            updateData(data)
        }
    }
but it's seems to be running sequentially somehow? Am I doing something wrong?
m

marstran

11/12/2018, 2:01 PM
The coroutineScope that is created by
runBlocking
waits for the
launch
to complete.
If you don't have any other scope to run it on, you could do
GlobalScope.launch { updateData(data) }
.
s

suppoze

11/12/2018, 2:08 PM
Yes, that's what I observed, however I don't understand why should it wait for
launch
to complete. E.g. in this example https://github.com/Kotlin/kotlinx.coroutines/blob/master/docs/coroutine-context-and-dispatchers.md#unconfined-vs-confined-dispatcher
runBlocking
is used in conjuction
launch
.
g

gildor

11/12/2018, 2:13 PM
It waits because this is how Structured Concurrency and coroutine scope work
m

marstran

11/12/2018, 2:13 PM
It because
runBlocking
creates a new
CoroutineScope
. A
CoroutineScope
will not complete before all child-coroutines complete. Look up "structured concurrency" 🙂
g

gildor

11/12/2018, 2:14 PM
In general this code with runBlocking + launch doesn't look good
Because it doesn't use any coroutine features and just adds overhead on top of thread executor
s

suppoze

11/12/2018, 2:19 PM
I tried with GlobalScope and it seems to be working as it should now 🙂 I'm pretty new to coroutine API and I might have been confusing dispatchers and coroutine scopes. Thank you for clearing this up for me! I'll look up structured concurrency In the end, I might leave the code as it was before because as you said @gildor it only adds overhead as of now 🙂
g

gildor

11/13/2018, 5:02 AM
Coroutine make sense if you want to get result or your
updateData
method mostly waits, so you can use async API instead of blocking
4 Views