Kotlin + Dagger - 为ViewModel工厂注入地图

时间:2017-09-04 19:21:17

标签: android kotlin dagger-2

我正在使用带有Dagger2的新架构组件,我想使用Factory类注入我的ViewModel。 Factory类本身是可注射的。当在Java中定义Factory类时,这一切都很有效,但是当我将它转换为Kotlin时,Dagger2不知道如何为构造函数生成Map,而在Java中它知道如何这样做。我认为不同之处在于,转换后,Factory类使用kotlin包中的Map,而不是java.util.Map包。如何让Dagger2为Factory构造函数生成地图?

这是工厂类

@ActivityScope
class MainActivityViewModelFactory @Inject
constructor(private val creators: Map<Class<out ViewModel>, 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)
        }

    }
}

这是错误

Error:java.util.Map<java.lang.Class<? extends android.arch.lifecycle.ViewModel>,? extends javax.inject.Provider<android.arch.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.

我尝试创建一个模块来提供地图,但这并没有帮助。

@ActivityScope
@Module
class MapModule {
    @Provides
    fun provideMap(): Map<Class<out ViewModel>, Provider<ViewModel>> = mutableMapOf()
}

1 个答案:

答案 0 :(得分:12)

我稍微修改了您的ViewModelFactory代码:

@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)
        }

    }
}

你能尝试一下吗? 我添加了@JvmSuppressWildcards注释。

有关详细信息,请查看: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.jvm/-jvm-suppress-wildcards/index.html

编辑: 您可以在我的仓库中找到现场演示:https://github.com/savepopulation/dc-tracker