Skip to content

Instantly share code, notes, and snippets.

@roman-tikonov
Created August 20, 2021 13:49
Show Gist options
  • Save roman-tikonov/5e398e89b73aa21e0f4826f6fe405e3b to your computer and use it in GitHub Desktop.
Save roman-tikonov/5e398e89b73aa21e0f4826f6fe405e3b to your computer and use it in GitHub Desktop.
A variation of FragmentViewModelLazy with added [SavedStateHandle] support
/**
* A variation of [Fragment.viewModels] with added [SavedStateHandle] support
*/
@MainThread
inline fun <reified VM : ViewModel> Fragment.savedStateViewModels(
noinline viewModelProducer: (SavedStateHandle) -> VM
) = createViewModelLazy(
viewModelClass = VM::class,
storeProducer = { this.viewModelStore },
savedStateRegistryOwnerProducer = { this },
viewModelProducer = viewModelProducer
)
/**
* A variation of [Fragment.activityViewModels] with added [SavedStateHandle] support
*/
@MainThread
inline fun <reified VM : ViewModel> Fragment.savedStateActivityViewModels(
noinline viewModelProducer: (SavedStateHandle) -> VM
) = createViewModelLazy(
viewModelClass = VM::class,
storeProducer = { requireActivity().viewModelStore },
savedStateRegistryOwnerProducer = { requireActivity() },
viewModelProducer = viewModelProducer
)
/**
* Helper method for creation of [ViewModelLazy] with [SavedStateHandle] support.
*/
@MainThread
fun <VM : ViewModel> createViewModelLazy(
viewModelClass: KClass<VM>,
storeProducer: () -> ViewModelStore,
savedStateRegistryOwnerProducer: () -> SavedStateRegistryOwner,
viewModelProducer: (SavedStateHandle) -> VM
): ViewModelLazy<VM> {
val factoryProducer = {
object : AbstractSavedStateViewModelFactory(savedStateRegistryOwnerProducer(), null) {
@Suppress("UNCHECKED_CAST")
override fun <T : ViewModel?> create(key: String, modelClass: Class<T>, handle: SavedStateHandle) = viewModelProducer(handle) as T
}
}
return ViewModelLazy(viewModelClass, storeProducer, factoryProducer)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment