首页 > 解决方案 > 在 response.await() 之后返回的 Kotlin 协程

问题描述

我正在尝试制作一个连接到 api 的 android 应用程序,为此我正在使用 Kotlin Coroutines 和 Retrofit。我正在关注本教程(https://android.jlelse.eu/android-networking-in-2019-retrofit-with-kotlins-coroutines-aefe82c4d777)试图设置我自己的 api,但我偶然发现了一个问题。我无法从 api 获取任何数据,因为我无法处理响应。

我对协程了解不多,所以我不明白这里有什么问题。如果我运行调试并逐行运行,它每次都能完美运行,但如果我运行应用程序,它只会打印 TestPoint1。它也不会抛出任何错误,响应总是 200 OK。我试图结合

val standings = service.getStandings()

val response = standings.await()

进入一行,之后它也不能用于调试。它在启动协程后继续执行代码。

val service = ApiFactory.footballApi

GlobalScope.launch(Dispatchers.Main) {
    val standings = service.getStandings()
    try {
        Log.d("TAG", "TestPoint1")
        val response = standings.await()
        Log.d("TAG", "TestPoint2")
        if(response.isSuccessful){
            //store data
        }else{
            Log.d("MainActivity ",response.errorBody().toString())
        }
    }catch (e: Exception){
        Log.d("TAG", "Error")
    }
}

标签: androidkotlinretrofitkotlin-coroutines

解决方案


切换Dispatchers.MainDispatchers.IO。您不能在主线程上提出该请求。协程需要协程上下文才能知道它们将在哪个线程中运行。为此,该Dispatchers课程为您提供了一些选择。目前,您正在发出Dispatchers.Main无法执行的请求,因为从 API 获取数据需要另一个线程。IO 是网络调用的正确线程。

笔记 :

还请检查:互联网许可,互联网连接。


推荐阅读