Learn Simple Android Compose Flow Lifecycle Handling With Counter
<p>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.</p>
<p>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.</p>
<h1>A Simple Flow</h1>
<p>To create a simple counter, I have the flow below that increments every second, in my ViewModel.</p>
<pre>
val counter = <em>flow </em><strong>{
</strong>var value = 0
while (true) {
emit(value++)
delay(1000)
}
<strong>}</strong></pre>
<p>In my Composable Function triggered from the MainActivity, I just collect it as a state variable and display it.</p>
<pre>
val stateVariable = viewModel.counter.<em>collectAsState</em>(0)<em>Text</em>("${stateVariable.value}")</pre>
<p>This works. But there’s one problem.</p>
<h2>It got reset on rotation!</h2>
<p>Whenever I rotate the screen (portrait to landscape), the number restarts again!</p>
<p>Initially, I was surprised to see the counter reset, wondering why that happens, given ViewModel will survive through the screen rotation (configuration changed).</p>
<p>Then I realized, upon rotation, the MainActivity got destroyed, where the counter flow got recollected again.</p>
<p><a href="https://medium.com/mobile-app-development-publication/learn-simple-android-compose-flow-lifecycle-handling-with-counter-36d62c88a2cd">Website</a></p>
<p> </p>