android - 在 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")
}
}
解决方案
切换Dispatchers.Main
到Dispatchers.IO
。您不能在主线程上提出该请求。协程需要协程上下文才能知道它们将在哪个线程中运行。为此,该Dispatchers
课程为您提供了一些选择。目前,您正在发出Dispatchers.Main
无法执行的请求,因为从 API 获取数据需要另一个线程。IO 是网络调用的正确线程。
笔记 :
还请检查:互联网许可,互联网连接。
推荐阅读
- javascript - Nextjs | Why getInitialProps is not generating one page per result (SEO)?
- javascript - HTML5Canvas, remembering the last instance made visible
- python - 创建一个时间表,让一群人互相交谈 - 有限制
- woocommerce - 如何划分或拆分 woocommerce 价格?
- python - 编程新手。为什么我的 Python 代码在这种情况下除外?
- javascript - 向 Vercel 上的简单 Next.js Web 应用程序添加基本密码保护的最佳方法是什么?
- html - 我可以在 html 组件中使用接口,但不能在打字稿中使用
- python - 当我尝试克隆不存在的存储库时,如何阻止 git 询问凭据?
- c# - C# 变量类型
- node.js - 本地 Firebase 函数上的 Express 应用