import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import androidx.compose.runtime.*
import androidx.compose.material3.Text
data class CounterUiState(val count: Int = 0, val loading: Boolean = false)
class CounterViewModel : ViewModel() {
private val _uiState = MutableStateFlow(CounterUiState())
val uiState: StateFlow<CounterUiState> = _uiState.asStateFlow()
fun increment() {
_uiState.update { it.copy(count = it.count + 1) }
}
fun loadFromNetwork() {
viewModelScope.launch {
_uiState.update { it.copy(loading = true) }
kotlinx.coroutines.delay(500)
_uiState.update { it.copy(count = 42, loading = false) }
}
}
}
@Composable
fun CounterScreen(vm: CounterViewModel) {
val state by vm.uiState.collectAsState() // lifecycle-aware collect
Text("count: ${state.count}, loading: ${state.loading}")
}
Create a free account and build your private vault. Share publicly whenever you want.