Package dagger.hilt.android.scopes
Annotation Interface ViewModelScoped
Scope annotation for bindings that should exist for the life of a a single
ViewModel.
Use this scope annotation when you want to define a dependency in the ViewModelComponent for which a single instance will be provided
across all other dependencies for a single HiltViewModel-annotated ViewModel. Other
ViewModels that request the scoped dependency will receive a different instance. For sharing the
same instance of a dependency across all ViewModels use a scope from one of the parent
components of dagger.hilt.android.components.ViewModelComponent, such as Singleton or ActivityRetainedScoped.
For example:
@Module
@InstallIn(ViewModelComponent.class)
public final class ViewModelMovieModule {
@Provides
@ViewModelScoped
public static MovieRepository provideRepo(SavedStateHandle handle) {
return new MovieRepository(handle.getString("movie-id"));
}
}
public final class MovieDetailFetcher {
@Inject MovieDetailFetcher(MovieRepository movieRepo) {
// ...
}
}
public final class MoviePosterFetcher {
@Inject MoviePosterFetcher(MovieRepository movieRepo) {
// ...
}
}
@HiltViewModel
public class MovieViewModel extends ViewModel {
@Inject
public MovieViewModel(MovieDetailFetcher detailFetcher, MoviePosterFetcher posterFetcher) {
// Both detailFetcher and posterFetcher will contain the same instance of
// the MovieRepository.
}
}
- See Also: