0

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:

  1. 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.

  1. I have a ViewModel associated with my Fragment and I register my observers to the fragment view's lifecycle. This means that I get notified during onStart. 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 because onResume must be called before the FragmentManager 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?

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
TheHebrewHammer
  • 3,018
  • 3
  • 28
  • 45

1 Answers1

0

As per the Navigation 1.0.0-alpha03 release notes:

FragmentNavigator now ignores navigation operations after FragmentManager has saved state, avoiding “Can not perform this action after onSaveInstanceState” exceptions b/110987825

So upgrading to alpha03 should remove this error.

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443