import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewmodel.compose.viewModel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.delay
class MainActivity : ComponentActivity() {
override fun onCreate(savedInstanceState: android.os.Bundle?) {
super.onCreate(savedInstanceState)
setContent {
FlowCounterScreen()
}
}
}
class CounterViewModel : ViewModel() {
val counterFlow: Flow<Int> = flow {
var count = 0
while(true) {
emit(count)
count++
delay(1000L)
}
}
}
@Composable
fun FlowCounterScreen(counterViewModel: CounterViewModel = viewModel()) {
val count by counterViewModel.counterFlow.collectAsState(initial = 0)
Text(text = "Current count: $count")
}We created a counterFlow in the CounterViewModel that emits an increasing integer every second using a while(true) loop with delay(1000L). In the Compose UI, we collect this flow as state using collectAsState with an initial value of 0. This way, the UI automatically updates the displayed count every second as new values are emitted from the flow.
This example shows the basics of Kotlin Flow: creating a flow, emitting values over time, and collecting them in the UI reactively.