[英]Which is better to use for API calls Dispatcher.IO or Dispatcher.Main?
Hei, I am using a MVVM archetectural patern in my android application.嘿,我在我的 android 应用程序中使用了 MVVM 架构模式。 I wanted to have api calls from my Viewmodel using
coroutinescope.lauch{}
Do I need to specify the Dispatcher as Dispatcher.IO
as it will be exicuted in a IO thread or just use the Dispathcer provided by the viewmodel which is Dispatcher.Main
我想使用
coroutinescope.lauch{}
我是否需要将 Dispatcher 指定为Dispatcher.IO
,因为它将在 IO 线程中执行,或者只使用 Dispatcher.Main 视图模型提供的Dispatcher.Main
There is an extension property on ViewModel
class, called viewModelScope
which works on Dispatcher.Main
context by default. ViewModel
class 上有一个名为viewModelScope
的扩展属性,它默认在Dispatcher.Main
上下文中工作。 You can use it to call your api functions if they are suspend
, eg:你可以用它来调用你的 api 函数,如果它们是
suspend
的话,例如:
viewModelScope.launch {
apiFunction()
// do other stuff
}
suspend fun apiFunction() { ... }
It is OK to call suspend
functions on Dispatchers.Main
context, they will suspend a coroutine but not block the Main Thread
.可以在
Dispatchers.Main
上下文中调用suspend
函数,它们将挂起协程但不会阻塞Main Thread
。
If your API functions are not suspend
you can convert them to suspend
functions by switching context to Dispatchers.IO
using withContext()
function. Or if API functions use callbacks you can consider using suspendCoroutine
or suspendCancellableCoroutine
.如果您的 API 函数未
suspend
,您可以通过使用withContext()
function 将上下文切换到Dispatchers.IO
将它们转换为suspend
函数。或者如果 API 函数使用回调,您可以考虑使用suspendCoroutine
或suspendCancellableCoroutine
。 Example of using withContext
:使用
withContext
的示例:
viewModelScope.launch {
apiSuspendFunction()
// do other stuff
}
suspend fun apiSuspendFunction() = withContext(Dispatchers.IO) {
apiNonSuspendFunction()
}
fun apiNonSuspendFunction() { ... }
For api call Dispatcher.IO is better对于 api 调用 Dispatcher.IO 更好
for more info了解更多信息
https://proandroiddev.com/kotlin-coroutines-in-android-summary-1ed3048f11c3 https://proandroiddev.com/kotlin-coroutines-in-android-summary-1ed3048f11c3
https://miro.medium.com/max/720/1*K-5ZG6rVR5Dl9J5E3Rx7eA.pnghttps://miro.medium.com/max/720/1*K-5ZG6rVR5Dl9J5E3Rx7eA.png
And in your case you use mvvm so more better to use ViewModelScope在你的情况下你使用 mvvm 所以更好地使用 ViewModelScope
viewModelScope.launch {
// operation
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.