Bảng Điều Khiển Ôn Phỏng Vấn Android
Kotlin • MVVM • Flow • REST API • Compose • Testing
Về Lộ trình kiến thức0/6
P0 - Bắt buộc vững
Coroutines + Flow
Phần xác suất bị hỏi cao nhất sau MVVM: xử lý async đúng scope, dispatcher và lifecycle.
Khái niệm chính
- suspend function trả một giá trị; Flow emit nhiều giá trị (cold).
- StateFlow giữ state mới nhất (UI); SharedFlow cho event.
- Gọi IO trên Dispatchers.IO, cập nhật UI trên Main.
- Collect lifecycle-aware: collectAsStateWithLifecycle / repeatOnLifecycle.
ViewModel expose StateFlow<UiState>
class UserViewModel(
private val repository: UserRepository
) : ViewModel() {
private val _uiState = MutableStateFlow<UiState>(UiState.Loading)
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
fun loadUsers() {
viewModelScope.launch {
_uiState.value = UiState.Loading
try {
_uiState.value = UiState.Success(repository.getUsers())
} catch (e: CancellationException) {
throw e // không nuốt cancellation
} catch (e: Exception) {
_uiState.value = UiState.Error(e.message ?: "Lỗi")
}
}
}
}Checklist
Tick những gì bạn đã nắm chắc
Lỗi thường gặp
- •Dùng `GlobalScope` thay vì `viewModelScope` gây leak coroutine.
- •Collect Flow không lifecycle-aware (thiếu `repeatOnLifecycle`/`collectAsStateWithLifecycle`).
- •Chạy IO trên `Dispatchers.Main` làm block UI.
Câu trả lời mẫu
suspend function trả về một giá trị, còn Flow là luồng emit nhiều giá trị. StateFlow là hot stream giữ giá trị mới nhất cho UI state, SharedFlow hợp cho event. Em gọi API trong `viewModelScope` với `Dispatchers.IO` và collect bằng `collectAsStateWithLifecycle` để không leak.
Câu hỏi liên quan