在另一个 withContext 中调用一个(kotlin 协程)withContext 是否安全?
Is it safe to call a (kotlin coroutine) withContext within another withContext?
我有这个简单的代码片段:
fun setMapIcon(bitmapDescriptor: BitmapDescriptor?,
coordinateId:Long?, clickListener: (Double,Double) -> Unit ){
lifecycleScope.launchWhenStarted {
withContext(Dispatchers.IO){
//Do some heavy work that needs many variables
withContext(Dispatchers.Main){
//Publish variables
}
//Do more heavy work
withContext(Dispatchers.Main){
//Publish more variables
//call `lambda` clickListener
}
}
}
如果您担心上述代码会导致任何问题,请放心,语义定义明确,它将按预期工作。至于该不该做,developer.android.com有下文
suspend fun fetchDocs() { // Dispatchers.Main
val result = get("developer.android.com") // Dispatchers.Main
show(result) // Dispatchers.Main
}
suspend fun get(url: String) = // Dispatchers.Main
withContext(Dispatchers.IO) { // Dispatchers.IO (main-safety block)
/* perform network IO here */ // Dispatchers.IO (main-safety block)
} // Dispatchers.Main
}
withContext() does not add extra overhead compared to an equivalent
callback-based implementation. Furthermore, it's possible to optimize
withContext() calls beyond an equivalent callback-based implementation
in some situations. For example, if a function makes ten calls to a
network, you can tell Kotlin to switch threads only once by using an
outer withContext(). Then, even though the network library uses
withContext() multiple times, it stays on the same dispatcher and
avoids switching threads.
我有这个简单的代码片段:
fun setMapIcon(bitmapDescriptor: BitmapDescriptor?,
coordinateId:Long?, clickListener: (Double,Double) -> Unit ){
lifecycleScope.launchWhenStarted {
withContext(Dispatchers.IO){
//Do some heavy work that needs many variables
withContext(Dispatchers.Main){
//Publish variables
}
//Do more heavy work
withContext(Dispatchers.Main){
//Publish more variables
//call `lambda` clickListener
}
}
}
如果您担心上述代码会导致任何问题,请放心,语义定义明确,它将按预期工作。至于该不该做,developer.android.com有下文
suspend fun fetchDocs() { // Dispatchers.Main
val result = get("developer.android.com") // Dispatchers.Main
show(result) // Dispatchers.Main
}
suspend fun get(url: String) = // Dispatchers.Main
withContext(Dispatchers.IO) { // Dispatchers.IO (main-safety block)
/* perform network IO here */ // Dispatchers.IO (main-safety block)
} // Dispatchers.Main
}
withContext() does not add extra overhead compared to an equivalent callback-based implementation. Furthermore, it's possible to optimize withContext() calls beyond an equivalent callback-based implementation in some situations. For example, if a function makes ten calls to a network, you can tell Kotlin to switch threads only once by using an outer withContext(). Then, even though the network library uses withContext() multiple times, it stays on the same dispatcher and avoids switching threads.