我在 Android 应用程序中使用 MVVM 架构模式。我想使用 coroutinescope.lauch{}
从我的 ViewModel
进行 API 调用 我是否需要将 Dispatcher 指定为 Dispatcher.IO
在 IO 线程中执行还是只使用 ViewModel 提供的 Dispatcher,即 Dispatcher.Main?
最佳答案
ViewModel
类上有一个扩展属性,名为 viewModelScope
默认情况下,它适用于 Dispatcher.Main
上下文。如果您的 api 函数挂起
,您可以使用它来调用它们,例如:
viewModelScope.launch {
apiFunction()
// do other stuff
}
suspend fun apiFunction() { ... }
可以在Dispatchers.Main
上下文中调用挂起
函数,它们会挂起协程,但不会阻塞主线程
。
如果您的 API 函数不是 suspend
,您可以使用 withContext 将上下文切换到
函数。或者,如果 API 函数使用回调,您可以考虑使用 Dispatchers.IO
,将它们转换为 suspend
函数()suspendCoroutine
或 suspendCancellableCoroutine
。使用 withContext
的示例:
viewModelScope.launch {
apiSuspendFunction()
// do other stuff
}
suspend fun apiSuspendFunction() = withContext(Dispatchers.IO) {
apiNonSuspendFunction()
}
fun apiNonSuspendFunction() { ... }
关于android - Dispatcher.IO 和 Dispatcher.Main 哪个更适合用于 API 调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73878845/