Hi all, Is there a Kotlin coroutine implementation...
# coroutines
s
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
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
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
It waits because this is how Structured Concurrency and coroutine scope work
m
It because
runBlocking
creates a new
CoroutineScope
. A
CoroutineScope
will not complete before all child-coroutines complete. Look up "structured concurrency" 🙂
g
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
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
Coroutine make sense if you want to get result or your
updateData
method mostly waits, so you can use async API instead of blocking