Parallel work in suspend function: Is it safe to use coroutinescope?

Viewed 497

I am experimenting a bit with kotlin coroutines, and I asked my self, how to perform multiple work inside one and the same suspend function (e.g call the network and the local database at the same time). Researching this problem led me to the following solution:

suspend fun doWorkInParallel() {
    coroutineScope {
        val networkCall = async { // stuff  }
        val databaseCall = async { // stuff }
        awaitAll(networkCall, databaseCall)
    }
}

Here are my questions:

  1. Is using the above approach correct or is there another way in performing parallel work in one and the same suspend function
  2. Does the other "coroutineScope" leak anything when I call the suspend function?
  3. Is the work done in parallel?
  4. What happens, when both the networkCall and the databaseCall access one and the same object / change one and the same object (e.g inside the networkCall a variable is set to State X and inside the databaseCall the variable is set to Stata Y)
2 Answers

This code is perfectly fine, it is exactly how you should perform parallel computing with coroutines. If you don't need return values of both calls, you can replace async() with launch() and remove awaitAll() line. coroutineScope() automatically waits for all its children to finish, so you don't need to do this manually.

  1. Yes, this is the correct way.
  2. I'm not sure what do you mean. You don't leak anything here.
  3. Yes, as long as you use coroutine dispatcher backed by multiple threads (this is usually the case), both calls will run in parallel.
  4. This is a typical case of sharing a mutable state. You need to somehow synchronize access to shared variables. It depends on your specific case.

i have a one question. Why you use coroutineScope? I think that you are already inside in suspend function.

Related