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]

但这是我的问题.虽然这是在主线程中运行的,但下面的代码适用于执行网络调用的我.

viewModelScope.launch {
    userRepo.login(email, password)
}

Here userRepo.login(email, password) is suspend function, which calls Retrofit suspend function.

那么,如果我当前的线程是主线程,这是如何工作的呢?

推荐答案

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相关问答推荐

映射中列表类型的Kotlin可空接收器?

关键字';在When Kotlin When-语句中

如何接受任何派生类KClass

有没有一种简单的方法来识别物体?

在 Kotlin 中将两个字节转换为 UIn16

Kotlin - 如何避免在密封类的 when() 语句中转换第二个变量

在协程上下文中重新抛出异常

如果带注释的成员未被特定块包围,则发出 IDE 警告

Lets plot Kotlin中的多轴比例

如何使用函数类型或 lambdas 作为 Kotlin 上下文接收器的类型?

Kotlin 条件格式字符串

如何在 kotlin @Parcelize 中使用 null

Kotlin 中多个 init 块的用例?

`this@classname` 在 Kotlin 中是什么意思?

包括登录Elvis operator?

参数不匹配;SimpleXML

Kotlin - 错误:Could not find or load main class _DefaultPackage

如何在伴随对象中使用泛型

比较Kotlin的NaN

是否可以在不使用class的情况下将 Mockito 与 Kotlin 一起使用?