Dagger2 ViewModel 無法提供 ViewModel@Binds ViewModelProvider 工廠的



我已经实现了对ViewModels注入的支持,符合中等文章和谷歌回购

不幸的是,我cannot be provided without an @Provides-annotated method.收到错误,无法深入了解它。

我已将项目迁移到AndroidX。我已经尝试了许多在StackOverflow上可用的答案,但没有成功。

应用组件

@Singleton
@Component(
        modules = [
            AndroidInjectionModule::class,
            AppModule::class,
            MainActivityModule::class,
            LoginActivityModule::class,
            DispatcherActivityModule::class]
)
interface AppComponent {
    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(application: Application): Builder
        fun build(): AppComponent
    }
    fun inject(androidApplication: BeeApp)
}

应用模块

@Module(includes = [ViewModelModule::class])
class AppModule {
...(i provide non-related other object here)
}

视图模型模块

@Suppress("unused")
@Module
abstract class ViewModelModule {
    @Binds
    @IntoMap
    @ViewModelKey(UserProfileViewModel::class)
    abstract fun bindUserViewModel(userProfileViewModel: UserProfileViewModel): ViewModel
    @Binds
    abstract fun bindViewModelFactory(viewModelFactory: DaggerViewModelFactory): ViewModelProvider.Factory
}

dagger视图模型工厂

@Singleton
@Suppress("UNCHECKED_CAST")
class DaggerViewModelFactory @Inject constructor(private val viewModelsMap: Map<Class<out ViewModel>, @JvmSuppressWildcards Provider<ViewModel>>) :
        ViewModelProvider.Factory {
    override fun <T : ViewModel> create(modelClass: Class<T>): T {
        val creator = viewModelsMap[modelClass] ?: viewModelsMap.asIterable().firstOrNull {
            modelClass.isAssignableFrom(it.key)
        }?.value ?: throw IllegalArgumentException("unknown model class $modelClass")
        return try {
            creator.get() as T
        } catch (e: Exception) {
            throw RuntimeException(e)
        }
    }
}

片段

class UserProfileFragment : BaseFragment(), Injectable {
    @Inject
    lateinit var viewModelFactory: ViewModelProvider.Factory
    lateinit var profileViewModel: UserProfileViewModel
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        profileViewModel = ViewModelProviders.of(this, viewModelFactory)
                .get(UserProfileViewModel::class.java)
    }
(...)
}

视图模型


class UserProfileViewModel @Inject constructor(userAccountRepository: UserAccountRepository) : ViewModel() {
    val userAccount: LiveData<Resource<UserAccount>> = userAccountRepository.loadUserAccount(true)
}

任何帮助将不胜感激。

这是由 Kotlin kapt 在 1.3.30 版问题跟踪器上的问题引起的

更改为上一个/更新的版本

相关内容

  • 没有找到相关文章