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

Oleg Siboglov

12/24/2019, 4:16 PM
I would appreciate it if anyone could give me some feedback. I have a class that makes use of
withContext
functions since the majority of the use cases require that the code runs sequentially. However, I have one use case where I need to run two of these functions concurrently and then combine the results. My question is if there is would be something wrong with wrapping the
withContext
functions with an
async
function.
Copy code
GlobalScope.launch {
        val deferredOne = async { doSomeWork() }
        val deferredTwo = async { doSomeWork() }
    }

suspend fun doSomeWork() = withContext(<http://Dispatchers.IO|Dispatchers.IO>) {
    // Do some work here
}
d

Dominaezzz

12/24/2019, 4:18 PM
Should be fine.
👍 1
t

tseisel

12/24/2019, 11:25 PM
Note: if your goal is to combine the result from multiple operations, I suggest wrapping those async calls into a
coroutineScope
block to make sure that the failure of one will cancel the other (structured concurrency).
g

gildor

12/24/2019, 11:33 PM
It's completely fine In general to do that, but your code snippet is incorrect, you essentially ignore all errors from async. If you don't care about returning result, use launch, or don't forget to call await()
No need to wrap to coroutineScope again, launch already scope and it will be cancelled if any of async will fail
o

Oleg Siboglov

12/24/2019, 11:38 PM
Yes, the code snippet is incomplete. I was just using it as a reference in case what I wrote wasn’t clear. Thank you for the feedback.
3 Views