Created
July 20, 2018 20:02
-
-
Save paulocns/9809f4000aa0b14f621e92f0df17ab07 to your computer and use it in GitHub Desktop.
This file contains 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
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