Last active
May 10, 2018 10:55
-
-
Save rohankandwal/a01d94a94832121c797aea5f0f94b033 to your computer and use it in GitHub Desktop.
CustomViewModelFactory - Used to provide ViewModels with all injections available for that particular Activity/Fragment/Service
This file contains hidden or 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
@Singleton | |
public class CustomViewModelFactory implements ViewModelProvider.Factory { | |
private final Map<Class<? extends ViewModel>, Provider<ViewModel>> creators; | |
@Inject | |
CustomViewModelFactory(Map<Class<? extends ViewModel>, Provider<ViewModel>> creators) { | |
this.creators = creators; | |
} | |
@NonNull | |
@SuppressWarnings("unchecked") | |
@Override | |
public <T extends ViewModel> T create(@NonNull Class<T> modelClass) { | |
Provider<? extends ViewModel> creator = creators.get(modelClass); | |
if (creator == null) { | |
for (Map.Entry<Class<? extends ViewModel>, Provider<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.get(); | |
} 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