I have an app using AndroidX's Navigation library, but I'm getting odd behavior. Particularly around my app going in/out of the background. Here are two examples:
- In a simple on click listener in a Fragment I have:
(Kotlin)
button.setOnClickListener {
findNavController().popBackStack()
}
From this, I see crashes saying it threw an IllegalStateException
since it ran after onSaveInstanceState
.
- I have a
ViewModel
associated with myFragment
and I register my observers to the fragment view's lifecycle. This means that I get notified duringonStart
. Some key events, such as login state determine the app's navigation. In my case I have a splash screen that could go to either a login screen or the main screen. Once a user completes login, I reset the navigation (taking me back to the splash screen). Now the auth state is ready and I want to navigate to the main fragment, this throws an error often becauseonResume
must be called before theFragmentManager
is considered ready. I get an error saying I'm in the middle of a transaction and I can't add a new one. To mediate this I had to write this strange bit of code:
(Kotlin)
private fun safeNavigateToMain() {
if (fragmentManager == null) {
return
}
if (!isResumed) {
view?.post { safeNavigateToMain() }
return
}
try {
findNavController().navigate(R.id.main)
} catch (tr: Throwable) {
view?.post { safeNavigateToMain() }
}
}
Does anyone know how I can get the navigation controller to play nice with the fragment lifecycles without having to add these workarounds?