Florian
10/24/2020, 9:22 AMclass ProfileFragment : Fragment() {
...
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val navController = findNavController()
val currentBackStackEntry = navController.currentBackStackEntry!!
val savedStateHandle = currentBackStackEntry.savedStateHandle
savedStateHandle.getLiveData<Boolean>(LoginFragment.LOGIN_SUCCESSFUL)
.observe(currentBackStackEntry, Observer { success ->
if (!success) {
val startDestination = navController.graph.startDestination
val navOptions = NavOptions.Builder()
.setPopUpTo(startDestination, true)
.build()
navController.navigate(startDestination, null, navOptions)
}
})
}
...
}
What is the benefit of this approach over the old approach from the codelab, where the LoginFragment just handles its back button itself:
requireActivity().onBackPressedDispatcher.addCallback(viewLifecycleOwner) {
navController.popBackStack(R.id.mainFragment, false)
}
The second approach seems much simpler and less repetitive