Skip to content

Instantly share code, notes, and snippets.

@L-Briand
Created June 1, 2022 08:21
Show Gist options
  • Save L-Briand/e35b2d80144c4ec613474c5288b3eb62 to your computer and use it in GitHub Desktop.
Save L-Briand/e35b2d80144c4ec613474c5288b3eb62 to your computer and use it in GitHub Desktop.
Get an Activity ViewModel in compose
/** 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>())
}
@fallaw90
Copy link

fallaw90 commented Feb 8, 2023

Awesome! Thank You for this

@phongbm
Copy link

phongbm commented Mar 2, 2023

Thank you. It work like a charm.

@skauss
Copy link

skauss commented Apr 19, 2023

thanks

@abinhho
Copy link

abinhho commented Jun 7, 2023

Nice but...How to destroy activityViewModel?

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