例如,我们要在两个Fragment之间共享一个ViewModel:
@AndroidEntryPoint
class FirstFragment : Fragment() {
@Inject
lateinit var sharedViewModel: SharedViewModel
...
override fun onAttach(context: Context) {
super.onAttach(context)
// 注入依赖项
lifecycleScope.launchWhenStarted {
sharedViewModel = hiltViewModel()
}
}
}
@AndroidEntryPoint
class SecondFragment : Fragment() {
@Inject
lateinit var sharedViewModel: SharedViewModel
...
override fun onAttach(context: Context) {
super.onAttach(context)
// 注入依赖项
lifecycleScope.launchWhenStarted {
sharedViewModel = hiltViewModel()
}
}
}
例如,我们要在两个Fragment之间共享一个Repository:
@ActivityScoped
class SharedRepository @Inject constructor() {
...
}
@AndroidEntryPoint
class FirstFragment : Fragment() {
@Inject
lateinit var sharedRepository: SharedRepository
...
}
@AndroidEntryPoint
class SecondFragment : Fragment() {
@Inject
lateinit var sharedRepository: SharedRepository
...
}