Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
ViewModelFactory for Dagger2
* Constructs a ViewModelFactory with dependencies
class ViewModelFactory @Inject constructor(
private val creators: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>
) : ViewModelProvider.Factory {
override fun <T : ViewModel> create(modelClass: Class<T>): T {
var creator = creators[modelClass]
if (creator == null) {
creator = creators.entries.firstOrNull {
return@firstOrNull modelClass.isAssignableFrom(it.key)
if (creator == null) {
throw IllegalArgumentException("Unknown model class $modelClass, have you declared this class in ViewModelModule?")
try {
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment