Dispatcher.IO 和 Dispatcher.Main 哪个更适合用于 API 调用?

Spr*_*eek 4 android kotlin android-mvvm android-viewmodel kotlin-coroutines

我在 Android 应用程序中使用 MVVM 架构模式。我想从我的 using 进行 API 调用我ViewModel需要coroutinescope.lauch{}指定 Dispatcher 因为Dispatcher.IO它将在 IO 线程中执行,还是只使用由 提供的 Dispatcher ViewModelDispatcher.Main

Ser*_*gey 5

ViewModel类上有一个扩展属性,称为默认情况下viewModelScope适用于Dispatcher.Main上下文。如果是的话,你可以用它来调用你的 api 函数suspend,例如:

viewModelScope.launch {
    apiFunction()
    // do other stuff
}

suspend fun apiFunction() { ... }
Run Code Online (Sandbox Code Playgroud)

suspend在上下文中调用函数是可以的Dispatchers.Main,它们会挂起协程但不会阻塞Main Thread.


如果您的 API 函数不是,suspend您可以suspend通过将上下文切换到Dispatchers.IOusing withContext()function 将它们转换为函数。或者,如果 API 函数使用回调,您可以考虑使用suspendCoroutinesuspendCancellableCoroutine。使用示例withContext

viewModelScope.launch {
    apiSuspendFunction()
    // do other stuff
}

suspend fun apiSuspendFunction() = withContext(Dispatchers.IO) { 
    apiNonSuspendFunction()
}

fun apiNonSuspendFunction() { ... }
Run Code Online (Sandbox Code Playgroud)

  • 可以在“Dispatchers.Main”上下文中调用“挂起”函数,它们将挂起协程但不会阻塞主线程。 (2认同)