我已经实现了对ViewModels注入的支持 medium article 和googleRepo
不幸的是,我得到了错误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
}
@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)
}
任何帮助将不胜感激。