使用MVVM+RXJAVA+KOIN的Kotlin电商APP不同排序RecyclerView内容相同如何修复
问题原因
代码存在三处核心问题导致所有RecyclerView内容一致:
- 热门商品列表
popular_product_rv绑定的适配器和最新商品列表共用了同一个productListAdapter,请求到的热门商品数据被赋值给了完全没有绑定到任何RecyclerView的productListAdapter2 - 适配器数据更新后没有调用刷新方法,会导致列表内容不更新
- 若Koin依赖配置中
ProductListAdapter是单例(single)声明,两次inject会得到同一个实例,也会导致内容一致
修复方案
1. 修改MainFragment中onViewCreated逻辑
替换原有onViewCreated代码为以下内容:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) // 初始化最新商品列表 latest_product_rv.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false) latest_product_rv.adapter = productListAdapter productListAdapter.productOnClickedListener = this // 初始化热门商品列表 popular_product_rv.layoutManager = LinearLayoutManager(requireContext(), RecyclerView.HORIZONTAL, false) popular_product_rv.adapter = productListAdapter2 productListAdapter2.productOnClickedListener = this val bannerSlider = view.findViewById<ViewPager2>(R.id.bannerSliderMain) // 监听最新商品数据 mainViewModel.productLiveData.observe(viewLifecycleOwner){ productListAdapter.products = it as ArrayList<Product> productListAdapter.notifyDataSetChanged() } // 监听热门商品数据 mainViewModel.productLiveData1.observe(viewLifecycleOwner){ productListAdapter2.products = it as ArrayList<Product> productListAdapter2.notifyDataSetChanged() } }
2. 检查Koin配置
确保你的Koin模块中ProductListAdapter的声明为factory,示例:
// 错误写法(单例,所有注入得到同一个实例) single { ProductListAdapter() } // 正确写法(每次注入生成新实例) factory { ProductListAdapter() }
内容的提问来源于stack exchange,提问作者Parsa Gh
相关产品推荐
相关产品推荐

