Skip to content

Instantly share code, notes, and snippets.

@kenkoro
Last active April 10, 2025 08:23
Show Gist options
  • Save kenkoro/39ef04d05b93668a1d8b3bfb09bc0343 to your computer and use it in GitHub Desktop.
Save kenkoro/39ef04d05b93668a1d8b3bfb09bc0343 to your computer and use it in GitHub Desktop.
Shared hilt view-model w/ compose
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.ViewModel
import androidx.navigation.NavBackStackEntry
import androidx.navigation.NavHostController
@Composable
inline fun <reified T : ViewModel> NavBackStackEntry.sharedHiltViewModel(
navController: NavHostController,
): T {
val navGraphRoute = destination.parent?.route ?: return hiltViewModel()
val parentEntry =
remember(this) {
navController.getBackStackEntry(navGraphRoute)
}
return hiltViewModel(parentEntry)
}
@kenkoro
Copy link
Author

kenkoro commented Sep 22, 2024

Here, you should use destination.parent?.startDestinationRoute instead of just route bc it's null - idk why exactly

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment