kotlin 使用Flow时,不会在recyclerView中重新加载列表

wkyowqbh  于 2023-01-17  发布在  Kotlin
关注(0)|答案(1)|浏览(177)

我正在训练一个简单的应用程序来播放电影,我使用MVVM模式和流程。

问题

这是我的家,可通过芯片

过滤
我点击一部电影,详细信息屏幕出现,然后我回到主页,这就是结果:

使用logcat,主屏幕会获得要显示的电影列表,但不会显示在recyclerview(使用diffUtil)中。
下面是我的代码片段:

@AndroidEntryPoint
class Home2Fragment : Fragment() {
    private val TAG = Home2Fragment::class.simpleName
    private var _binding: FragmentHome2Binding? = null
    private val binding: FragmentHome2Binding
        get() = _binding!!
    private val viewModel: HomeViewModel by viewModels()

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        _binding = FragmentHome2Binding.inflate(inflater, container, false)

        return binding.root
    }

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

            initChipGroupSpecificMovieList()

            val adapter = MovieAdapter()
            sectionRv.setHasFixedSize(true)
            sectionRv.adapter = adapter
            viewLifecycleOwner.lifecycleScope.launch {
                viewLifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.STARTED) {
                    viewModel.movieListBySpecification.collectLatest {
                        Log.d(TAG, "onViewCreated: received list")
                        adapter.addItems(it)
                    }
                }

            }
        }
    }

    private fun FragmentHome2Binding.initChipGroupSpecificMovieList() {
        val sortByMap = HomeViewModel.Companion.MovieListSpecification.values()
        chipGroup.removeAllViews()
        for (specification in sortByMap) {
            val chip = Chip(context)
            chip.isCheckable = true
            chip.id = specification.ordinal
            chip.text = getString(specification.nameResource)
            chip.setOnCheckedChangeListener { _, isChecked ->
                if (isChecked)
                    viewModel.setMovieListSpecification(specification)
            }
            chipGroup.addView(chip)
        }
        chipGroup.check(sortByMap.lastIndex - sortByMap.size + 1)//check first element

    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

}

看起来在代码行中,我尝试在适配器中插入电影列表,这不会添加它们,因为可能通过diffUtil,它发现这是以前的列表,所以它不会加载它。然而,它也不会显示以前的列表,可能的解决方案?

tjvv9vkg

tjvv9vkg1#

作为java代码你可以使用这个

@Override
    public void onResume() {
        super.onResume();
        if(it.size() > 0) {
            adapter.addItems(it)
        }
    }

相关问题