Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
ViewModelFactory for Dagger2
/**
* Constructs a ViewModelFactory with dependencies
*/
@Singleton
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)
}?.value
if (creator == null) {
throw IllegalArgumentException("Unknown model class $modelClass, have you declared this class in ViewModelModule?")
}
}
try {
@Suppress("UNCHECKED_CAST")
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