Package dagger.hilt.android.scopes
Annotation Type ViewModelScoped
-
@Scope @Retention(CLASS) public @interface ViewModelScoped
Scope 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
ViewModelComponent
for which a single instance will be provided across all other dependencies for a singleHiltViewModel
-annotatedViewModel
. OtherViewModel
s that request the scoped dependency will receive a different instance. For sharing the same instance of a dependency across allViewModel
s use a scope from one of the parent components ofdagger.hilt.android.components.ViewModelComponent
, such asSingleton
orActivityRetainedScoped
.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