在Android Studio中如何用Dagger Hilt为RepositoryImpl提供Callbacks接口?
解决方案
要让Hilt为RepositoryImpl提供Callbacks实例(由MainFragment实现),需要调整依赖作用域并编写对应的实例提供逻辑,具体步骤如下:
1. 调整Repository的作用域并添加Callbacks提供方法
原RepositoryModule绑定在SingletonComponent中,会导致单例Repository持有Fragment级别的Callbacks实例,引发生命周期不匹配和内存泄漏问题。需将模块安装到FragmentComponent,让Repository生命周期与Fragment绑定,同时添加Callbacks的提供方法:
@Module @InstallIn(FragmentComponent::class) abstract class RepositoryModule { @Binds abstract fun bindRepository(repositoryImpl: RepositoryImpl): Repository // 从当前Fragment实例获取Callbacks实现 @Provides fun provideCallbacks(fragment: Fragment): Callbacks { // 强制检查Fragment是否实现接口,避免运行时类型转换异常 check(fragment is Callbacks) { "当前Fragment未实现Callbacks接口" } return fragment } }
2. 保持现有类的修改不变
RepositoryImpl构造函数无需改动,Hilt会自动注入Callbacks:
class RepositoryImpl @Inject constructor( private val callbacks: Callbacks ) : Repository { }
MainFragment继续实现Callbacks并保留@AndroidEntryPoint注解:
@AndroidEntryPoint class MainFragment : Fragment(), Callbacks { @Inject lateinit var repository: Repository override fun onSomethingHappened() { // 实现回调逻辑 } }
关键说明
FragmentComponent是Hilt为每个Fragment实例创建的专属组件,能够直接获取当前Fragment实例,因此可以通过@Provides方法将其转换为Callbacks接口返回。- 类型检查
check(fragment is Callbacks)用于提前暴露错误,避免未实现接口的Fragment注入Repository时出现运行时崩溃。 - 调整后
Repository的生命周期与Fragment一致,彻底避免了单例持有Fragment实例导致的内存泄漏问题。
内容的提问来源于stack exchange,提问作者Junior
相关产品推荐
相关产品推荐

