Kotlin 协程 viewModelScope 中的改造调用 [英] Retrofit call in Kotlin Coroutines viewModelScope
问题描述
最近我更新了我的 ViewModel
以使用新的 viewModelScope
.从它的实现中,我看到 Dispatchers.Main.immediate
被设置为 viewModelScope
的默认 CoroutineDispatcher
.
Recently I've updated my ViewModel
to use new viewModelScope
. From its' implementation, I see that Dispatchers.Main.immediate
is set as the default CoroutineDispatcher
for viewModelScope
.
因此,当在 viewModelScope.launch
中打印当前的 Thread
时,它会给出 Thread[main,5,main]
So when printing the current Thread
in viewModelScope.launch
it gives Thread[main,5,main]
但这是我的问题.虽然它在主线程中运行,但以下代码对我来说适用,它执行网络调用.
But here is my question. Although this runs in Main Thread, the following code works for me which performs a network call.
viewModelScope.launch {
userRepo.login(email, password)
}
这里的userRepo.login(email, password)
是suspend
函数,调用Retrofit
suspend
函数.
Here userRepo.login(email, password)
is suspend
function, which calls Retrofit
suspend
function.
那么这是如何工作的,如果我的当前线程是主线程?
So how this works, if my Current Thread is Main Thread?
推荐答案
之所以有效,是因为 Retrofit 的 suspend
实现委托给 Call
.这意味着它默认已经在自己的后台执行器上执行,而不是使用调用者的 Dispatcher
.
It works because Retrofit's suspend
implementation delegates to Call<T>.enqueue
. This means it already executes on its own background executor by default instead of using the caller's Dispatcher
.
这篇关于Kotlin 协程 viewModelScope 中的改造调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!