Kotlin
Beginner
1 min read
ViewModel and StateFlow
Example
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
data class UiState(
val isLoading: Boolean = false,
val items: List<String> = emptyList(),
val error: String? = null,
)
class ItemViewModel : ViewModel() {
private val _uiState = MutableStateFlow(UiState())
val uiState: StateFlow<UiState> = _uiState.asStateFlow()
init { loadItems() }
fun loadItems() {
viewModelScope.launch {
_uiState.update { it.copy(isLoading = true, error = null) }
try {
val result = repository.getItems() // suspend fun
_uiState.update { it.copy(isLoading = false, items = result) }
} catch (e: Exception) {
_uiState.update { it.copy(isLoading = false, error = e.message) }
}
}
}
}
// Fragment (collector side)
// lifecycleScope.launch {
// viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
// viewModel.uiState.collect { state ->
// binding.progressBar.isVisible = state.isLoading
// adapter.submitList(state.items)
// state.error?.let { showError(it) }
// }
// }
// }