当我从一个片段回到另一个片段的时候,我的观察者总是在发力

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

我正在使用导航组件,我有 片段A片段B,从 片段A 我发送一个对象到 片段B 的安全参数,并导航到它。

override fun onSelectableItemClick(position:Int,product:Product) {
        val action = StoreFragmentDirections.actionNavigationStoreToOptionsSelectFragment(product,position)
        findNavController().navigate(action)
    }

现在,在我的 片段B 我想把这些数据传递给 片段A 再次,我用

  btn_add_to_cart.setOnClickListener {button ->     
 findNavController().previousBackStackEntry?.savedStateHandle?.set("optionList",Pair(result,product_position))
                findNavController().popBackStack()
            }

然后在 片段A,我把这些数据与

findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Pair<MutableList<ProductOptions>,Int>>("optionList")
            ?.observe(viewLifecycleOwner, Observer {
                storeAdapter.updateProductOptions(it.second,it.first)
            })

现在,这是很好的工作,但如果我去从 片段A片段B 并按下后退键,上面的观察者又会重复我的当前数据发射,有没有办法在我只按下 btn_add_to_cart 扣子 片段B ?

android android-fragments kotlin android-viewmodel android-architecture-navigation
1个回答
0
投票

从你的代码中并不清楚你的最后一段代码是在哪里调用的--你在哪里添加了一个名为fun onSelectableItemClick(position:Int,...)的函数。观察家实时数据. 我猜测它在其中一个方法里面 onResume()onViewStateRestored() 或任何其他生命周期回调,每当你返回到 片段A片段B. 如果是这样的话,那么你就向 实时数据 而LiveData的任何观察者都会收到当前值的即时更新。

将这段代码移到一个回调方法中,这个方法在一个片段的生命周期中只被调用一次。

© www.soinside.com 2019 - 2024. All rights reserved.