使用 kotlin 中的协程从 Fragment 中的 Room Dao 获取数据

问题描述 投票:0回答:1

如何从片段中的

cactusDao
获取数据?

package fragment

import ...

private const val ARG_PARAM1 = "param1"
private const val ARG_PARAM2 = " param2"

private lateinit var cactusDao: CactusDao
private lateinit var customerAdapter: CustomerAdapter
private var customerList = listOf<Customer>()

private lateinit var recyclerView: RecyclerView


class CustomerFragment : Fragment() {
    private var param1: String? = null
    private var param2: String? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        arguments?.let {
            param1 = it.getString(ARG_PARAM1)
            param2 = it.getString(ARG_PARAM2)
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_customer, container, false)
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: String, param2: String) = CustomerFragment().apply {
            arguments = Bundle().apply {
                putString(ARG_PARAM1, param1)
                putString(ARG_PARAM2, param2)
            }
        }
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        cactusDao = CactusDatabase.getInstance(requireContext()).cactusDao

        viewLifecycleOwner.lifecycleScope.launch {
            customerList = cactusDao.getAllCustomers()
        }

        recyclerView = view.findViewById(R.id.customer_fragment_recycler_view)
        customerAdapter = CustomerAdapter(customerList)
        recyclerView.adapter = customerAdapter
    }

}

doe 这个答案 我尝试使用

viewLifecycleOwner.lifecycleScope.launch{}
块能够将数据异步写入我的
customerList
,但它仍然为空。

我尝试了

runBlocking{}
GlobalScope(Dispatchers.IO)
甚至
lifeCycleScope.launch
,但没有帮助。你有解决办法吗?

顺便说一句,我没有使用ViewModel。

android kotlin android-room dao coroutine
1个回答
0
投票

你的问题是你没有等待结果。在

onViewCreated
中,您启动一个协程并完成
onViewCreated
的其余部分,从空的
customerList
获取当前值。

您需要让 UI 的其余部分知道数据已更改。

private var customerList = MutableLiveData<List<Customer>>()

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recyclerView = view.findViewById(R.id.customer_fragment_recycler_view)

    cactusDao = CactusDatabase.getInstance(requireContext()).cactusDao
    viewLifecycleOwner.lifecycleScope.launch(Dispatchers.IO) {
        customerList.postValue(cactusDao.getAllCustomers())
    }

    customerList.observe(viewLifecycleOwner) { customers ->
        customerAdapter = CustomerAdapter(customerList)
        recyclerView.adapter = customerAdapter
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.