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