【发布时间】:2021-10-10 04:57:12
【问题描述】:
我正在阅读 Google 文档中有关 Kotlin 协程的信息。建议我将 withContext(Dispacher.IO) 用于与主安全不同的线程。但我有一个问题,fetchData() 在服务器响应之前完成,所以 fetchData() 返回 null 结果。任何我感谢的帮助。
https://developer.android.com/kotlin/coroutines/coroutines-best-practices#main-safe
class GameRemoteDataSource @Inject constructor(val api : GameApi) {
val IODispatcher: CoroutineDispatcher = Dispatchers.IO
suspend fun fetchData() : Resource<ListGameResponse> {
var resource : Resource<ListGameResponse> = Resource.loading(null)
withContext(IODispatcher){
Log.d("AAA Thread 1", "${Thread.currentThread().name}")
api.getAllGame(page = 1).enqueue(object : Callback<ListGameResponse>{
override fun onResponse(
call: Call<ListGameResponse>,
response: Response<ListGameResponse>
) {
if(response.code()==200){
resource = Resource.success(response.body())
}else{
resource = Resource.success(response.body())
}
Log.d("AAA code",response.code().toString())
}
override fun onFailure(call: Call<ListGameResponse>, t: Throwable) {
resource = Resource.error(t.message.toString(),null)
Log.d("AAA Thread", "${Thread.currentThread()}")
}
})
Log.d("AAA Thread", "${Thread.currentThread()}")
Log.d("AAA resource",resource.data.toString()+ resource.status.toString())
}
return resource
}
}
【问题讨论】:
-
虽然该问题的答案可能被用来解决这个问题,但它并没有解释为什么 OP 的代码不起作用,并且在使用 Retrofit 时没有必要使用
suspendCoroutine,它已经内置暂停功能。
标签: android kotlin coroutine withcontext