asad.awadia
07/31/2020, 1:02 PMfun 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?bezrukov
07/31/2020, 1:48 PMfrom 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:
fun main() {
val apiRequest = 1
val apiResponse = runBlocking {
withContext(<http://Dispatchers.IO|Dispatchers.IO>) { someApiCallThatReturns(apiRequest) }
}
}
or even
fun main() {
val apiRequest = 1
val apiResponse = runBlocking(<http://Dispatchers.IO|Dispatchers.IO>) {
someApiCallThatReturns(apiRequest)
}
}
asad.awadia
07/31/2020, 1:55 PMbezrukov
07/31/2020, 1:59 PMasad.awadia
07/31/2020, 2:09 PM