虽然 Dagger 实现我有以下错误。请帮我解决。
dagger/component/AppComponent.java:10: 错误:[com.example.testproject.app.dagger.component.PostLoginComponent.inject(com.example.testproject.view.photo.PhotoListActivity)] com.example.testproject .data.UserStore 不能在没有@Inject 构造函数或@Provides-annotated 方法的情况下提供。
我的理解 - 我已经创建了 AppComponent 和 AppModule,它们是 PostLoginComponent 和 PostLoginModule 的父组件(因为它们是子组件)。 photoListViewModel 被注入到 PhotoListActivity 中。 photoListViewModel 由 postLoginComponent 和 PostLoginModule 提供。现在 photoListViewModel 需要 UserStore 作为 AppModule 中存在的依赖项。 因此,根据我的理解,父模块中的所有对象都可用于子模块。 在这种情况下,来自 AppModule 的 UserStore 应该可用于 PostLoginModule 中的 PhotoListViewModel。
但根据错误未提供 UserStore。
@Module
abstract class AppModule {
@Module
companion object {
@Provides
fun provideUserStore(context: Context): UserStore {
return UserStore(context)
}
}
}
@Component(modules = [AppModule::class])
interface AppComponent {
fun postLoginComponent(): PostLoginComponent.Builder
@Component.Builder
interface Builder {
@BindsInstance
fun bindData(context: Context): Builder
fun build(): AppComponent
}
}
@Module
abstract class PostLoginModule {
@Binds
@IntoMap
@ViewModelKey(PhotoListViewModel::class)
abstract fun bindViewModel(viewModel: PhotoListViewModel): ViewModel
@MustBeDocumented
@Target(AnnotationTarget.FUNCTION)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class ViewModelKey(val value: KClass<out ViewModel>)
}
@Subcomponent(modules = [PostLoginModule::class])
interface PostLoginComponent {
fun inject(activity: PhotoListActivity)
@Subcomponent.Builder
interface Builder {
fun build(): PostLoginComponent
}
}
class PhotoListActivity() : PostLoginActivity() {
var adapter = PhotoListAdapter(
mutableListOf(
PhotoItem("", "akash"),
PhotoItem("", "akash"),
PhotoItem("", "akash"),
PhotoItem("", "akash")
)
)
@Inject
lateinit var factory: ViewModelFactory
private val photoListViewModel: PhotoListViewModel by lazy {
ViewModelProvider(this, factory).get(PhotoListViewModel::class.java)
}
override fun setLayoutId(): Int? {
return R.layout.activity_photo_list
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
TestApp.get(this).appComponent().postLoginComponent().build().inject(this)
initView()
}
private fun initView() {
textView.setOnClickListener {
adapter.clearData()
}
rvPhotoList.initRecyclerView {
it.layoutManager = LinearLayoutManager(this)
it.adapter = adapter
}
adapter.setItemClickListener(OnRecyclerViewOnItemClickListener { parent, view, position -> })
rvPhotoList.addErrorView(EmptyErrorView(this))
getPhotoList()
}
private fun getPhotoList() {
adapter.addItems(photoListViewModel.getPhotoList())
}
}
class PhotoListViewModel @Inject constructor(userStore: UserStore) : BaseViewModel() {
fun getPhotoList(): List<PhotoItem> {
return mutableListOf(
PhotoItem("", "aher"),
PhotoItem("", "aher"),
PhotoItem("", "aher"),
PhotoItem("", "aher")
)
}
}