Created
December 11, 2021 17:16
-
-
Save SumeraMartin/e31a9bf7103d50d803665d1fe93a0a81 to your computer and use it in GitHub Desktop.
ViewModel without Hilt in Jetpack Compose
This file contains 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
@Composable | |
inline fun <reified VIEW_MODEL : ViewModel> viewModelFactory( | |
key: String? = null, | |
crossinline viewModelCreator: () -> VIEW_MODEL | |
): VIEW_MODEL = viewModel( | |
modelClass = VIEW_MODEL::class.java, | |
key = key, | |
factory = object : ViewModelProvider.Factory { | |
override fun <VIEW_MODEL : ViewModel> create(modelClass: Class<VIEW_MODEL>): VIEW_MODEL { | |
val viewModel = viewModelCreator() as? VIEW_MODEL ?: error("Unexpected viewModel") | |
if (viewModel is BaseViewModel<*>) { | |
viewModel.onCreated() | |
} | |
return viewModel | |
} | |
} | |
) | |
@Composable | |
fun rememberHomeViewModel() = viewModelFactory { | |
... create ViewModel somehow ... | |
} | |
@Composable | |
fun HomeScreen( | |
navigation: NavigationDestinations, | |
viewModel: HomeViewModel = rememberHomeViewModel() | |
) { | |
... | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment