Created
June 1, 2022 08:21
-
-
Save L-Briand/e35b2d80144c4ec613474c5288b3eb62 to your computer and use it in GitHub Desktop.
Get an Activity ViewModel in compose
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
/** Try to fetch a viewModel in [store] */ | |
@Composable | |
inline fun <reified T : ViewModel, S : ViewModelStoreOwner> viewModelInStore(store: S): Result<T> = | |
runCatching { | |
var result: Result<T>? = null | |
CompositionLocalProvider(LocalViewModelStoreOwner provides store) { | |
result = runCatching { viewModel(T::class.java) } | |
} | |
result!!.getOrThrow() | |
} | |
/** Try to fetch a viewModel with current context (i.e. activity) */ | |
@Composable | |
inline fun <reified T : ViewModel> safeActivityViewModel(): Result<T> = runCatching { | |
val activity = LocalContext.current as? ViewModelStoreOwner | |
?: throw IllegalStateException("Current context is not a viewModelStoreOwner.") | |
return viewModelInStore(activity) | |
} | |
/** Force fetch a viewModel inside context viewModelStore */ | |
@Composable | |
inline fun <reified T : ViewModel> activityViewModel(): T = safeActivityViewModel<T>().getOrThrow() | |
@Composable | |
fun MyComposeElement( | |
fragmentViewModel: ComposeViewModel = viewModel(), | |
activityViewModel: ComposeViewModel = activityViewModel() | |
) { | |
assert(fragmentViewModel != activityViewModel) | |
assert(fragmentViewModel == viewModel<ComposeViewModel>()) | |
assert(activityViewModel == activityViewModel<ComposeViewModel>()) | |
} |
Thank you. It work like a charm.
thanks
Nice but...How to destroy activityViewModel?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Awesome! Thank You for this