首页 > 解决方案 > 无法在 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它都可以正常工作。我不明白为什么会发生这种情况以及我应该如何解决这个问题。提前致谢!:)

标签: androidkotlincoroutine

解决方案


推荐阅读