I am using Navigation Component in my app , recently it was working correctly but after updating project to AndroidX
I am getting error navigation destination DESTINATION_NAME is unknown to this NavController
only if that destination(Which I'm going to open) is previously closed from itself using navController.popBackStack()
. Also, There is no error if I close DESTINATION fragment from MainActivity
, But Error only Occurs fragment is closed from itself using popBackStack
. like below
DestinationFragment
viewModelOfActivity.handleBackButton.observe(this, Observer {
Navigation.findNavController(requireActivity(), R.id.main_nav_host).popBackStack()
//CALLING popBackStack() HERE CAUSING PROBLEM WHEN REOPNING THIS DESTINATION(or frg ) AGIAN
})
MainActivity
override fun onBackPressed() {
if (myViewModel.isDefaultBehaviour.value == true) {
super.onBackPressed()
} else{
myViewModel.handleBackButton.value=true
//NO ERROR IF HANDLE BACK BUTTON HERE ie->findNavController(R.id.main_nav_host).popBackStack()
//INSTEAD OF myViewModel.handleBackButton
}
}
I Have also checked related Question but no help Similar Question.
NOTE: I am using the latest version of the navigation library (alpha05)
I was using SingleLiveEvent in DestinationFragment to observe back press from MainActivity as I have already mentioned this in my question. So the problem was in SingleLiveEvent
I noticed that I have accidently changed code of fun observe(owner: LifecycleOwner, observer: Observer<in T>)
to
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
super.observe(owner, observer)//Here is problem I was calling super twice in function
if (hasActiveObservers()) {
Log.w(TAG, "Multiple observers registered but only one will be notified of changes.")
}
super.observe(owner, Observer { t ->/** other code*//})
}
Here you can see I was calling super
function twice which calls onChanged
of observer twice in Fragment
, below code is called twice
Navigation.findNavController(requireActivity(), R.id.main_nav_host).popBackStack()
which popBackStack()
twice.
Then I have changed observe
function like below
@MainThread
override fun observe(owner: LifecycleOwner, observer: Observer<in T>) {
if (hasActiveObservers()) {
Log.w(TAG, "Multiple observers registered but only one will be notified of changes.")
}
super.observe(owner, Observer { t ->/** other code*//})
}
Now my code works fine