Kotlin + Dagger - inject Map for ViewModel factory

后端 未结 1 1092
谎友^
谎友^ 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, @JvmSuppressWildcards Provider>) : ViewModelProvider.Factory {
    
        override fun  create(modelClass: Class): T {
            var creator: Provider? = 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)
提交回复
热议问题