Kotlin + Dagger - inject Map for ViewModel factory

后端 未结 1 1090
谎友^
谎友^ 2020-12-05 12:26

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

相关标签:
1条回答
  • 2020-12-05 12:54

    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

    0 讨论(0)
提交回复
热议问题