哪个推荐在IO线程中使用postValue()或者在主线程中使用setValue() android kotlin li



我有视图模型,我使用实时数据。推荐使用哪一种,为什么?在主线程setValue或在IO线程postValue()或在主线程postValue()

fun getProductInfoFromWebService(barcode: String, url: String) {
viewModelScope.launch(Dispatchers.IO) {
val response = productInfoRepo.getProductInfoFromWebService(barcode, url)
withContext(Dispatchers.Main) {
_productInfoFromWebService.value = response
}
}
}

fun getProductInfoFromWebService(barcode: String, url: String) {
viewModelScope.launch(Dispatchers.IO) {
val response = productInfoRepo.getProductInfoFromWebService(barcode, url)
withContext(Dispatchers.Main) {
_productInfoFromWebService.postValue(response)
}
}
}

fun getProductInfoFromWebService(barcode: String, url: String) {
viewModelScope.launch(Dispatchers.IO) {
val response = productInfoRepo.getProductInfoFromWebService(barcode, url)
_productInfoFromWebService.postValue(response)
}
}

以上皆非。Android的一般惯例是将主线程设为默认值。这就是viewModelScope默认为Dispatchers.Main.immediate的原因。对于绝大多数已启动的协程,您不需要在启动站点更改调度器。

此外,如果需要的话,Kotlin协程约定将挂起函数内部委托给特定的分派器。永远不需要指定调度程序来调用挂起函数。

你的代码应该是这样的:

fun getProductInfoFromWebService(barcode: String, url: String) {
viewModelScope.launch {
_productInfoFromWebService.value = productInfoRepo.getProductInfoFromWebService(barcode, url)
}
}

如果你在launch块中直接调用阻塞函数,你通常会用withContext(Dispatchers.IO)包围该代码。但是,如果您正在调用挂起函数(除非您的挂起函数设计不当),这是不必要的。

最新更新