If you’ve already got Hilt up and running, and you’re willing to utilize the Navigation library for your Compose UI, the Hilt Navigation Compose library is a no brainer.
Essentially, what it allows you to do is get an Android Architecture ViewModel
scoped to a navigation destination.
Here’s my modified version of the example from the docs:
@Composable
fun MyApp() {
val navController = rememberNavController()
var startRoute by remember { mutableStateOf("example") }
NavHost(navController, startDestination = startRoute) {
composable("example") { backStackEntry ->
val viewModel: MyViewModel = hiltViewModel()
MyScreen(viewModel)
}
}
}
In this example you have a NavHost
setup that you’re using to navigate between screens. Inside your example
destination, you use the hiltViewModel()
function to get a ViewModel
scoped to the destination that can then be passed into the MyScreen
composable.
You may be wondering why this matters, as you could always use the viewModel()
method to get a ViewModel
in Compose. The key distinction here is scoping:
viewModel()
returns an existingViewModel
or creates a new one. By default, the returnedViewModel
is scoped to the enclosing activity, fragment or navigation destination, and is retained as long as the scope is alive.
If you’re utilizing Compose Navigation, it just makes sense to be able to scope View Models to the nav destination, and further separate from a direct connection to Fragments or Activities.