Change theme
Help
Press space for more information.
Show links for this issue (Shortcut: i, l)
Copy issue ID
Previous Issue (Shortcut: k)
Next Issue (Shortcut: j)
Sign in to use full features.
Vote: I am impacted
Notification menu
Refresh (Shortcut: Shift+r)
Go home (Shortcut: u)
Pending code changes (auto-populated)
View issue level access limits(Press Alt + Right arrow for more information)
Request for new functionality
View staffing
Description
Version used: 1.0.0-alpha05
Devices/Android versions reproduced on: Pixel 2
When building NavDirections from ViewModels I miss a method to build a NavDirections object that represents a popBackStack or a navigateUp event for the consumer Activity/Fragment.
The objective of this feature request is to build, from ViewModel classes, Navigation Directions that have no dependency on Navigation Controllers. These navigation events can be published in a LiveData observable that Fragments and Activities can observe and consume with a Navigation Controller to navigate according to the logic implemented in the ViewModel class and leaving the Activity/Fragment completely ignorant of navigation logic.
I currently implemented this with a sealed class where I wrap popBackStack events and NavDirections into my own NavigationDirection data structure like this code below, but it will be better if this was part of the Navigation library:
/**
* Sealed class that represents all the possible navigation destination directions that can be produced in a View Model
*/
sealed class NavigationDirection {
object NavigateBack : NavigationDirection()
data class Screen(val directions: NavDirections) : NavigationDirection()
}
fun NavController.navigateToNavigationDirection(direction: NavigationDirection) {
when (direction) {
NavigationDirection.NavigateBack -> this.popBackStack()
is NavigationDirection.Screen -> this.navigate(direction.directions)
}
}
// LiveData used in ViewModels
val mutableNavigationState = SingleLiveEvent<NavigationDirection>()
// Consumer code in Activity/Fragment
ViewModel.navigationState.observe(viewLifecycleOwner) {
findNavController().navigateToNavigationDirection(it)
}