Lifecycle-Aware Collection
lifecycleScope & repeatOnLifecycle
Collecting a `Flow` in a coroutine that keeps running while the screen is in the background wastes resources and can crash. `repeatOnLifecycle` starts/stops collection in sync with the lifecycle.
📚 Explanation
`lifecycleScope` cancels its coroutines when the owner is destroyed, but a long-lived `collect` would still run while the app is backgrounded. `repeatOnLifecycle(STARTED)` restarts the collection each time the screen reaches `STARTED` and cancels it on `STOPPED`, so flows are only collected when visible. In Compose, `collectAsStateWithLifecycle()` wraps this same safe pattern for you.
Note: Code execution is not available for Android/Kotlin in the browser. Use Android Studio to run and test the app.
import androidx.activity.ComponentActivityimport androidx.lifecycle.Lifecycleimport androidx.lifecycle.lifecycleScopeimport androidx.lifecycle.repeatOnLifecycleimport kotlinx.coroutines.launchclass FeedActivity : ComponentActivity() {private val viewModel: FeedViewModel by viewModels()override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)// lifecycleScope is cancelled when the Activity is destroyed.lifecycleScope.launch {// repeatOnLifecycle STARTS collecting when STARTED,// and CANCELS the block when the screen goes below STARTED.repeatOnLifecycle(Lifecycle.State.STARTED) {viewModel.uiState.collect { state ->render(state)}}}}}// In Compose, the equivalent helper is collectAsStateWithLifecycle():@Composablefun FeedScreen(viewModel: FeedViewModel) {val state by viewModel.uiState.collectAsStateWithLifecycle()FeedContent(state)}