而 Dagger 实现我有以下错误。请帮我解决它。
匕首/组件/AppComponent.java:10:错误:[com.example.testproject.app.dagger.component.PostLoginComponent.inject(com.example.testproject.view.photo.PhotoListActivity)] com.example.testproject.data。如果没有 @Inject 构造函数或 @Provides-annotated 方法,则无法提供 UserStore。
我的理解 - 我创建了 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")
)
}
}