Learn Android Development

Learn Simple Android Compose Flow Lifecycle Handling With Counter

Simple Design To Explain the Need for Handling Lifecycle in Compose and Flow

Photo by Lucas Santos on Unsplash

Sometimes when we try to understand Android Lifecycle, we crack our heads, wondering what scenario they are really important to tackle. Not understanding them often caused us to miss out on using them appropriately.

Here, I came up with a very simple design, i.e. a counter, that helps provides various simple scenarios of lifecycle one to take care of. Hope this helps.

A Simple Flow

To create a simple counter, I have the flow below that increments every second, in my ViewModel.

val counter = flow {
var value = 0
while (true) {
emit(value++)
delay(1000)
}
}

In my Composable Function triggered from the MainActivity, I just collect it as a state variable and display it.

val stateVariable = viewModel.counter.collectAsState(0)Text("${stateVariable.value}")

This works. But there’s one problem.

It got reset on rotation!

--

--