I have a repository called MainRepository with @ActivityRetainedScoped
@ActivityRetainedScoped
class MainRepository @Inject constructor( ... ) {
fun getCurrentUser(): Flow<User?> = callbackFlow { ... }
}
This repository is injected into multiple view models like this, because I need to use the same real-time data from firestore in different activities using callback flows
@HiltViewModel
class MainViewModel @Inject constructor(
mainRepository: MainRepository) : ViewModel() {
val user: LiveData<User?> = mainRepository.getCurrentUser().asLiveData()
}
and
@HiltViewModel
class ProgramViewModel @Inject constructor(
mainRepository: MainRepository): ViewModel() {
val user: LiveData<User?> = mainRepository.getCurrentUser().asLiveData()
}
Finally, I use my view models in my activities like this
val mainViewModel: MainViewModel by viewModels()
val currentUser by mainViewModel.user.observeAsState()
val programViewModel: ProgramViewModel by viewModels()
val currentUser by programViewModel.user.observeAsState()
I want to know when exactly will my repository will be destroyed, and of course, if there is a better way to do this please do mention it, my objective is to reduce multiple cloud firestore requests. I am new with Hilt
So, here your Repository will be created when your activity is created and destroyed when your activity is destroyed since you are using the @ActivityRetainedScoped
scope then your Repository will still survive during configuration changes but will create and destroy with the activity. And the activity to which your repository is belonged to.
Also, see the comment from hilt official doc:
ActivityRetainedComponent lives across configuration changes, so it is created at the first onCreate and last onDestroy.
But I guess you don't need to add the scoping into your repository since the repository always attaches with some feature activity and ViewModel and will fall the feature scope automatically.