@Scope
@Retention(value=CLASS)
public @interface ViewModelScoped
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 ViewModel
s that request the scoped dependency will receive a different instance. For sharing the
same instance of a dependency across all ViewModel
s 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. } }
HiltViewModel
,
ViewModelComponent