I\'m using the new Architecture Components with Dagger2 and I would like to inject my ViewModels using a Factory class. The Factory class is itself injectable. This all work
I modified your ViewModelFactory
code a bit:
@ActivityScope
class MainActivityViewModelFactory @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: Provider<out ViewModel>? = creators[modelClass]
if (creator == null) {
for ((key, value) in creators) {
if (modelClass.isAssignableFrom(key)) {
creator = value
break
}
}
}
if (creator == null) {
throw IllegalArgumentException("unknown model class " + modelClass)
}
try {
return creator.get() as T
} catch (e: Exception) {
throw RuntimeException(e)
}
}
}
Can you try with this?
I added @JvmSuppressWildcards
annotation.
For more information you can check: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-suppress-wildcards/index.html
Edit: You can find a live demo from my repo: https://github.com/savepopulation/dc-tracker