Created
December 23, 2025 10:39
-
-
Save rommansabbir/8709122a414c8b9dc6608b192ed370b4 to your computer and use it in GitHub Desktop.
A Composable function that simplifies the process of providing a ViewModel in both runtime and preview environments.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import androidx.compose.runtime.Composable | |
| import androidx.compose.ui.platform.LocalInspectionMode | |
| import androidx.hilt.navigation.compose.hiltViewModel | |
| import androidx.lifecycle.ViewModel | |
| /** | |
| * A Composable function that simplifies the process of providing a ViewModel in both | |
| * runtime and preview environments. | |
| * | |
| * In a standard runtime environment, it uses `hiltViewModel()` to retrieve a | |
| * Hilt-injected ViewModel instance. | |
| * | |
| * In a Compose preview environment (i.e., when `LocalInspectionMode.current` is true), | |
| * it returns a "fake" or mock instance of the ViewModel provided by the `fake` lambda. | |
| * This is useful for creating previews of Composables that depend on a ViewModel | |
| * without needing to set up the full Hilt dependency graph. | |
| * | |
| * @param VM The type of the ViewModel to be provided, which must extend [ViewModel]. | |
| * @param fake A lambda function that returns a fake or mock instance of the ViewModel. | |
| * This is only executed in preview mode. | |
| * @return The appropriate ViewModel instance for the current context (Hilt-injected or fake). | |
| * | |
| * @see [LocalInspectionMode] | |
| * @see [hiltViewModel] | |
| * | |
| * Example usage: | |
| * ``` | |
| * @Composable | |
| * fun MyScreen( | |
| * viewModel: MyViewModel = previewOrHiltViewModel { | |
| * // This block is only called in preview mode | |
| * MyViewModel(FakeRepository()) | |
| * } | |
| * ) { | |
| * // Screen content that uses the viewModel | |
| * } | |
| * | |
| * @Preview | |
| * @Composable | |
| * fun MyScreenPreview() { | |
| * MyApplicationTheme { | |
| * MyScreen() // Will use the fake MyViewModel | |
| * } | |
| * } | |
| * ``` | |
| */ | |
| @Composable | |
| inline fun <reified VM : ViewModel> previewOrHiltViewModel( | |
| fake: () -> VM | |
| ): VM { | |
| return if (LocalInspectionMode.current) { | |
| fake() | |
| } else { | |
| hiltViewModel<VM>() | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment