I have a LiveData observer on LiveBarcodeScanningFragment that observes barcode live data, after which if detected, BarcodeBottomSheetFragment will start (extend Fragment instead of BottomSheetDialogFragment which have more animations).
But here's the problem, the observer on LiveBarcodeScanningFragment triggered immediately after loading the fragment (Have implement SingleLiveEvent extend MutableLiveData in Google).
I have test AlertDialog can achieve my goal. In Debug mode, I saw that, when I use AlertDialog, it will finish observation, then open AlertDialog. When I dismiss the dialog, It will not retrigger the observation.
Here are my codes
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
update:
Here is my temporary solution, use add rather than replace like DialogFragment.show method do.
fm.beginTransaction()
.add(R.id.activity_live_barcode_container, frag)
.addToBackStack(fragTag).commit()