ViewModel là state holder của một màn hình: giữ và chuẩn bị dữ liệu cho UI, và sống qua configuration change (xoay màn hình, đổi dark mode) — Activity bị tạo lại nhưng ViewModel vẫn còn, không phải gọi API lại.
class ProductViewModel(
private val repo: ProductRepository,
savedState: SavedStateHandle,
) : ViewModel() {
private val id: Int = checkNotNull(savedState["id"])
val uiState: StateFlow<ProductUiState> = repo.observe(id)
.map { ProductUiState.Success(it) }
.stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), ProductUiState.Loading)
}Vai trò đúng theo hướng dẫn kiến trúc của Android:
- Nhận sự kiện từ UI, gọi xuống repository/use case (logic nghiệp vụ và gọi API nằm ở data/domain layer), rồi biến kết quả thành UI state.
- Chạy coroutine trong viewModelScope — tự huỷ khi ViewModel bị clear.
- Lấy ViewModel bằng viewModel()/hiltViewModel() trong Compose, hoặc by viewModels() trong Activity/Fragment.
Lưu ý: không giữ Activity, View hay context của Activity trong ViewModel — ViewModel sống lâu hơn chúng nên sẽ gây memory leak. ViewModel cũng không sống qua process death; dữ liệu nhỏ cần giữ lại (id, từ khoá tìm kiếm) thì lưu trong SavedStateHandle.