LiveData观察器在重新加载片段后启动新片段时触发,但AlertDialog没有



我在LiveBarcodeScanningFragment上有一个LiveData观察器,它观察条形码实时数据,之后如果检测到,BarcodeBottomSheetFragment将启动(扩展Fragment而不是BottomSheetDialogFragment,后者有更多动画(。

但问题是,LiveBarcodeScanningFragment上的观察者在加载片段后立即触发(在谷歌中实现SingleLiveEvent扩展MutableLiveData(。

我已经测试AlertDialog可以实现我的目标。在调试模式下,我看到当我使用AlertDialog时,它会完成观察,然后打开AlertDialog。当我关闭对话框时,它不会重新触发观察。

这是我的代码

wm= ViewModelProvider(this@LiveBarcodeScanningFragment).get(WorkflowModel::class.java)

wm.searchedProduct.observe(viewLifecycleOwner) { searchedRes ->
// THIS fragment = (LiveBarcodeScanningFragment)
//  extend fragment instead of BottomSheetDialogFragment,
//  it will open new fragment directly, block the observation,
// and occur the problem, when I return to THIS fragment(LiveBarcodeScanningFragment),
// it will run here again and again. (been observed to get changed )
// BG: BarcodeBottomSheetFragment replace THIS fragment.
/*
*  private fun openFragment(
*  fm: FragmentManager,
*  frag: BarcodeBottomSheetFragment, fragTag: String
*  ) {
*  fm.beginTransaction()
*      .replace(
*          R.id.activity_live_barcode_container,
*          frag
*      )
*      .addToBackStack(fragTag)
*      .commit()
*   }
* */
BarcodeBottomSheetFragment.openAddBarcodeToDatabaseAndCartPage(
parentFragmentManager,
getDeviceInfo(),
null,
wm.adapter!!,
searchedRes
)
// use Debug, I saw, it will finish observation, then open AlertDialog.
// will not re-trigger observation
AlertDialog.Builder(requireContext())
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(
android.R.string.yes
) { dialog, which -> }
.setNegativeButton(android.R.string.no, null)
.setIcon(android.R.drawable.ic_dialog_alert)
.show()
Timber.d("AlertDialog END... ")
}
// will not re-trigger observation

更新:

这是我的临时解决方案,使用添加而不是像DialogFragment.show方法那样替换。

fm.beginTransaction() 
.add(R.id.activity_live_barcode_container, frag)
.addToBackStack(fragTag).commit() 

但问题是,LiveBarcodeScanningFragment上的观测者在加载片段后立即触发

这是经过设计的。LiveData仅在数据更改时提供更新,但也仅向活动观察者提供更新。在此上下文中,活动是指应用程序组件的生命周期状态。因此,例如,如果您在片段的onResume函数中注册了观测者,那么当它恢复时,它将收到更新,从而触发AlertDialog。

您没有与您的observer调用共享代码,但如果还没有,您需要确保将其移动到onCreate。"观察LiveData对象"中的这一部分对此进行了最佳解释。