Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
545 views
in Technique[技术] by (71.8m points)

android - Dagger/MissingBinding java.util.Map<java.lang.Class<? extends ViewModel>,Provider<ViewModel>> cannot be provided without an @Provides-annotated method

This is how I'm trying to provide my ViewModelFactory:

@Suppress("UNCHECKED_CAST")
@Singleton
class ViewModelFactory @Inject constructor(
    private val viewModels: MutableMap<Class<out ViewModel>, Provider<ViewModel>>
) : ViewModelProvider.Factory {

    override fun <T : ViewModel?> create(modelClass: Class<T>): T = viewModels[modelClass]?.get() as T
}

@Target(AnnotationTarget.FUNCTION, AnnotationTarget.PROPERTY_GETTER, AnnotationTarget.PROPERTY_SETTER)
@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)

And this is how I'm binding the ViewModelFactory:

@Suppress("unused")
@Module
abstract class ViewModelModule  {
    @Binds
    internal abstract fun bindViewModelFactory(factory: ViewModelFactory): ViewModelProvider.Factory

    @Binds
    @IntoMap
    @ViewModelKey(MainViewModel::class)
    internal abstract fun mainViewModel(viewModel: MainViewModel): ViewModel
}

I'm receiving the following error during build:

di/Injector.java:9: error: [Dagger/MissingBinding] java.util.Map<java.lang.Class<? extends androidx.lifecycle.ViewModel>,javax.inject.Provider<androidx.lifecycle.ViewModel>> cannot be provided without an @Provides-annotated method.

From my Activity I'm trying to receive the ViewModelFactory this way:

@Inject
lateinit var viewModelFactory: ViewModelProvider.Factory
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I faced the same issue recently. Version Kotlin:1.3.40 Dagger:2.23.2 I tried following the solutions mentioned in this post and here

but none seemed to work. The annotation processor of Dagger is not playing well with KAPT and for the same reason, the builds are failing. This is also updated on Kotlin issue too.

For me, converting both the ViewModelKey and ViewModelFactory to java worked. For Dagger, the tracking issue can be found here.

Update Adding @JvmSuppressWildcards fixed the issue. Code looks like this:

private val providers: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...