Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 | 31 |
Tags
- Coroutines
- relay
- AWS
- Codeforces
- androidStudio
- livedata
- boj
- Kotlin
- 프로그래머스
- 암호학
- 코루틴
- 백준
- 쿠링
- activity
- Gradle
- Hilt
- Compose
- android
- GitHub
- 코드포스
- architecture
- textfield
- pandas
- MiTweet
- ProGuard
- Python
- Coroutine
- MyVoca
- Rxjava
- TEST
Archives
- Today
- Total
이동식 저장소
[Hilt] ViewModels 본문
Hilt는 Jetpack ViewModel을 생성자 주입할 수 있다. 생성자 주입이란 생성자에 @Inject
키워드를 붙이는 방식이다.
@HiltViewModel
class MainScreenViewModel @Inject constructor(
private val someData: Data
) : ViewModel() { /* ... */}
이제 @AndroidEntryPoint
어노테이션이 붙은 클래스에서 ViewModel 객체를 얻을 수 있다. by viewModels()
구문이 많이 사용된다. KTX(KoTlin eXtension) 구문 중 하나이다. 기차 아님.
@AndroidEntryPoint
class MyActivity : AppCompatActivity() {
private val mainViewModel: MainViewModel by viewModels()
}
Compose에서는 hiltViewModel()
을 쓴다.
@Composable
fun MainScreen(
modifier: Modifier = Modifier,
viewModel: MainScreenViewModel = hiltViewModel(),
) { ... }
View Model Scope
모든 ViewModel은 ViewModelComponent
에 의해 주입된다. ViewModelComponent
의 생명주기는 ViewModel
과 같다.
특정 의존성이 ViewModel
에서만 사용된다면 의존성을 @ViewModelScoped
에 scope해 보자. @ViewModelScoped
는 하나의 ViewModel
객체에 항상 같은 의존성 객체를 제공한다. 당연히 다른 ViewModel
객체는 다른 객체를 받는다. 여러 ViewModel
에 같은 객체가 주어져야 한다면 @ActivityRetainedScope
또는 @Singleton
을 사용해야 한다.
@ViewModelScoped
를 사용하여 여러 객체에 같은 의존성 객체를 주입하는 예시이다.
@Module
@InstallIn(ViewModelComponent::class)
internal object ViewModelMovieModule {
@Provides
@ViewModelScoped
fun provideRepo(handle: SavedStateHandle) = MovieRepository(handle.getString("movie-id"));
}
class MovieDetailFetcher @Inject constructor(
val movieRepo: MovieRepository
)
class MoviePosterFetcher @Inject constructor(
val movieRepo: MovieRepository
)
@HiltViewModel
class MovieViewModel @Inject constructor(
val detailFetcher: MovieDetailFetcher,
val posterFetcher: MoviePosterFetcher
) : ViewModel {
init {
// detailFetcher and posterFetcher는 같은 MovieRepository 객체를 참조한다.
}
}
'Primary > Android' 카테고리의 다른 글
[Hilt] Entry Points (0) | 2022.09.10 |
---|---|
[Hilt] Modules (0) | 2022.08.29 |
[Hilt] Android Entry Points (0) | 2022.08.11 |
[Hilt] Application (0) | 2022.08.11 |
[Android] 계정명이 한글일 때 test error 해결법 (0) | 2022.07.26 |
Comments