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

asad.awadia

07/31/2020, 1:02 PM
Copy code
fun main() {
  val apiRequest = 1
  var apiResponse = ""
  runBlocking {
    apiResponse = withContext(<http://Dispatchers.IO|Dispatchers.IO>) { someApiCallThatReturns(apiRequest) }
  }
}
is ‘returning responses’/‘sending arguments’ responses from one thread/coroutines on different didspatchers to another like this safe to do?
b

bezrukov

07/31/2020, 1:48 PM
in this particular case it's safe, but it's hard to answer your question in general, because it's unclear what
from one coroutine to another
means. In your example there are special conditions that make it safe: 1. order: the code after runBlocking is called strictly after the body of runBlocking 2. safe publication: apiResponse result will be visible to initial thread after completing runBlocking's body So if in your other cases both conditions are met (order and safe publication) it's safe. but if there are ways to avoid that, I would recommend to, because explicit logic is always better. your particular example can be easily rewritten to:
Copy code
fun main() {
  val apiRequest = 1
  val apiResponse = runBlocking {
    withContext(<http://Dispatchers.IO|Dispatchers.IO>) { someApiCallThatReturns(apiRequest) }
  }
}
or even
Copy code
fun main() {
  val apiRequest = 1
  val apiResponse = runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
      someApiCallThatReturns(apiRequest) 
  }
}
a

asad.awadia

07/31/2020, 1:55 PM
the two examples are syntax workarounds - but are still doing the same thing - ‘returning’ a value from one thread to another - but its safe to do so? I dont need a mutex or any other synchronisation primitve?
b

bezrukov

07/31/2020, 1:59 PM
yes, it's safe
a

asad.awadia

07/31/2020, 2:09 PM
thanks!