android - 无法在 CoroutineScope 中填充适配器
问题描述
我正在学习协程并尝试做一些小实验。我想从后端获取数据并使用 recyclerview 填充它们。
所以,要做到这一点:
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout....)
val linearLayoutManager = LinearLayoutManager(this)
recyclerview.layoutManager = linearLayoutManager
GlobalScope.launch {
val dataList = Repository().getData() //
runOnUiThread {
adapter = Adapter(dataList, ..., listener)
bodyPart.adapter = adapter
adapter.notifyDataSetChanged()
}
}
}
suspend fun getData(): List<data> = coroutineScope {
return@coroutineScope if (...) {
getFromApi()
} else {
getLocal()
}
}
但这根本不起作用。适配器函数 likeonCreateViewHolder
不会被调用。每当我将设置适配器数据的部分移到外部时,GlobalScope.launch
它都可以正常工作。我不明白为什么会发生这种情况以及我应该如何解决这个问题。提前致谢!:)
解决方案
推荐阅读
- javascript - Javascript 输入 UTC 字符串
- python - 由于命名空间为空,Python XPath lxml 无法读取 SVG 路径元素?
- c - 浮点函数总是返回 0.000000
- laravel - Laravel 分页在第一页后不起作用
- python-3.x - 关于使用 pydrive 列出所有文件
- java - Spring bean 销毁上的 System.exit() 是否有效?
- c++ - 代码块自动缩进突然停止工作(Windows 10)
- r - 使用 lapply 标准化 ts() 函数
- firebase - 使用 Firebase 无法登录的 Google Play 游戏
- matlab - 在Matlab中用二分法求解方程