I would appreciate it if anyone could give me some...
# coroutines
o
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
Should be fine.
đź‘Ť 1
t
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
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
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.