【问题标题】:Kotlin Coroutine returning after response.await()在 response.await() 之后返回的 Kotlin 协程
【发布时间】:2019-09-24 08:32:50
【问题描述】:

我正在尝试制作一个连接到 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")
    }
}

【问题讨论】:

    标签: android kotlin retrofit kotlin-coroutines


    【解决方案1】:

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

    注意:

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

    【讨论】:

      猜你喜欢
      • 2019-05-11
      • 2018-04-13
      • 2021-01-01
      • 2017-11-08
      • 2020-03-12
      • 2018-02-22
      • 1970-01-01
      • 2020-12-08
      • 1970-01-01
      相关资源
      最近更新 更多