【发布时间】:2020-05-03 22:35:37
【问题描述】:
我正在尝试从多个位置获取一些数据以填充 recyclerView。我曾经使用回调,效果很好,但需要将其重构为协程。
所以我有一个改造服务列表,并并行调用它们。然后我可以使用 onResponse 回调更新 recyclerView。我如何使用协程来实现这一点。
我尝试了类似的方法,但在我得到响应后触发了下一个呼叫:
runblocking {
for (service in services) {
val response = async(Dispatchers.IO) {
service.getResponseAsync()
}
adapter.updateRecyclerView(response.await())
}
}
使用另一种方法时,我遇到的问题是我无法返回主线程来更新我的用户界面,因为我正在使用启动并且无法等待响应:
runblocking {
services.foreach {
launch(Dispatcher.IO) {
val response = it.getResponseAsync()
}
withContext(Dispatcher.Main) {
adapter.updateRecyclerView(response)
}
}
}
我很感激每一个提示;) 帕特里克干杯
【问题讨论】:
-
runBlocking不应该在测试之外使用。它完全违背了使用协程的目的。出于好奇,您为什么选择使用它?我每天都在这里的问题中看到它,所以人们一定是从某个地方得到这个想法的。
标签: kotlin retrofit2 kotlin-coroutines