collectAsState is quietly leaking your work
Here is a line you have written a hundred times: val state by viewModel . data . collectAsState () It looks harmless. It is the standard way to turn a Flow into Compose state. And on a screen with live data, it quietly keeps working long after the user has walked away. The screen nobody is watching collectAsState starts collecting the flow and stops only when the composable leaves the…
The collectAsState function in Compose is commonly used to turn a Flow into Compose state. However, this seemingly harmless line of code can quietly leak work in the background, even when the user is not interacting with the screen. When the app is backgrounded, the composable remains composed, causing the collection to keep running and the ViewModel to continue fetching, computing, and pushing new state.
This can lead to unexpected battery and mobile data usage, as well as bugs caused by stale changes being displayed when the user returns.
To resolve this issue, the collectAsStateWithLifecycle function should be used instead. This function ties the collection to the lifecycle owner, stopping the collection when the lifecycle drops below STARTED and resuming it when the lifecycle comes back. By making collectAsStateWithLifecycle the default and plain collectAsState the exception, developers can ensure that work stops when the screen is not visible, saving resources and preventing bugs.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.