Skip to content

Instantly share code, notes, and snippets.

@paulocns
Created July 20, 2018 20:02
Show Gist options
  • Save paulocns/9809f4000aa0b14f621e92f0df17ab07 to your computer and use it in GitHub Desktop.
Save paulocns/9809f4000aa0b14f621e92f0df17ab07 to your computer and use it in GitHub Desktop.
public class ProjectViewModelFactory implements ViewModelProvider.Factory {
private final ArrayMap<Class, Callable<? extends ViewModel>> creators;
public ProjectViewModelFactory(ViewModelSubComponent viewModelSubComponent) {
creators = new ArrayMap<>();
creators.put(HomeFragmentViewModel.class, () -> viewModelSubComponent.homeFragmentViewModel());
creators.put(QueryViewModelArc.class, () -> viewModelSubComponent.queryViewModelArc());
}
@Override
public <T extends ViewModel> T create(Class<T> modelClass) {
Callable<? extends ViewModel> creator = creators.get(modelClass);
if (creator == null) {
for (Map.Entry<Class, Callable<? extends ViewModel>> entry : creators.entrySet()) {
if (modelClass.isAssignableFrom(entry.getKey())) {
creator = entry.getValue();
break;
}
}
}
if (creator == null) {
throw new IllegalArgumentException("Unknown model class " + modelClass);
}
try {
return (T) creator.call();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment