Skip to content

Instantly share code, notes, and snippets.

@vyachin
Created October 27, 2024 12:15
Show Gist options
  • Save vyachin/ec58b83d16b1cf9f7ff1a93af41008af to your computer and use it in GitHub Desktop.
Save vyachin/ec58b83d16b1cf9f7ff1a93af41008af to your computer and use it in GitHub Desktop.
Jetpack compose view model
package com.example.myapplication
import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.enableEdgeToEdge
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.padding
import androidx.compose.material3.Button
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.lifecycle.ViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
data class CounterUiState(val value: Int)
class CounterViewModel : ViewModel() {
private val _uiState = MutableStateFlow(CounterUiState(value = 0))
val uiState: StateFlow<CounterUiState> = _uiState.asStateFlow()
fun increase() {
_uiState.update { currentState ->
currentState.copy(
value = currentState.value + 1,
)
}
}
}
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
enableEdgeToEdge()
setContent {
Scaffold { innerPadding ->
val viewModel: CounterViewModel = viewModel()
val uiState by viewModel.uiState.collectAsStateWithLifecycle()
Column(modifier = Modifier.padding(innerPadding)) {
Button(
onClick = {
viewModel.increase()
}
) {
Text("Increase")
}
Text(text = uiState.value.toString())
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment