我有一个简单的代码片段:
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
}
}
}发布于 2021-07-02 05:43:35
如果您担心上面的代码会导致任何问题,那么请放心,语义是很好定义的,并且它会像预期的那样工作。至于你是否应该做这件事,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()不会增加额外的开销。此外,在某些情况下,可以在等效的基于回调的实现之外优化withContext()调用。例如,如果一个函数对一个网络进行了十次调用,您可以通过使用外部withContext()告诉Kotlin只切换一次线程。然后,即使网络库多次使用withContext(),它仍然停留在同一个dispatcher上,避免切换线程。
https://stackoverflow.com/questions/68199619
复制相似问题