Skip to content

Instantly share code, notes, and snippets.

@ramonrabello
Created July 28, 2020 03:00
Show Gist options
  • Save ramonrabello/08f1a9f438b71ed78e88336c984bbbd2 to your computer and use it in GitHub Desktop.
Save ramonrabello/08f1a9f438b71ed78e88336c984bbbd2 to your computer and use it in GitHub Desktop.
Hilt Series: Architecture Components com Hilt - HiltViewModelFactory.java
public final class HiltViewModelFactory extends AbstractSavedStateViewModelFactory {
private static final String KEY_PREFIX = "androidx.hilt.lifecycle.HiltViewModelFactory";
private final SavedStateViewModelFactory mDelegateFactory;
private final Map<String,
Provider<ViewModelAssistedFactory<? extends ViewModel>>> mViewModelFactories;
HiltViewModelFactory(
@NonNull SavedStateRegistryOwner owner,
@Nullable Bundle defaultArgs,
@NonNull SavedStateViewModelFactory delegateFactory,
@NonNull Map<String,
Provider<ViewModelAssistedFactory<? extends ViewModel>>> viewModelFactories) {
super(owner, defaultArgs);
this.mDelegateFactory = delegateFactory;
this.mViewModelFactories = viewModelFactories;
}
@NonNull
@Override
@SuppressWarnings("unchecked")
protected <T extends ViewModel> T create(@NonNull String key, @NonNull Class<T> modelClass,
@NonNull SavedStateHandle handle) {
Provider<ViewModelAssistedFactory<? extends ViewModel>> factoryProvider =
mViewModelFactories.get(modelClass.getName());
if (factoryProvider == null) {
...
return mDelegateFactory.create(KEY_PREFIX + ":" + key, modelClass);
}
return (T) factoryProvider.get().create(handle);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment