Package dagger.hilt.android.scopes
Annotation Type ViewModelScoped
-
@Scope @Retention(CLASS) public @interface ViewModelScopedScope annotation for bindings that should exist for the life of a a singleViewModel.Use this scope annotation when you want to define a dependency in the
ViewModelComponentfor which a single instance will be provided across all other dependencies for a singleHiltViewModel-annotatedViewModel. OtherViewModels that request the scoped dependency will receive a different instance. For sharing the same instance of a dependency across allViewModels use a scope from one of the parent components ofdagger.hilt.android.components.ViewModelComponent, such asSingletonorActivityRetainedScoped.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:
HiltViewModel,ViewModelComponent