You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MVVM+RXJAVA+KOIN的Kotlin电商APP不同排序RecyclerView内容相同如何修复

问题原因

代码存在三处核心问题导致所有RecyclerView内容一致:

  1. 热门商品列表popular_product_rv绑定的适配器和最新商品列表共用了同一个productListAdapter,请求到的热门商品数据被赋值给了完全没有绑定到任何RecyclerView的productListAdapter2
  2. 适配器数据更新后没有调用刷新方法,会导致列表内容不更新
  3. 若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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 19:57:04