Interview frequency: …
Short answer
Because repeatOnLifecycle automatically stops collecting the streams and cancels the coroutine when the screen goes to the background (such as onStop) and relaunches it on return, saving CPU and battery.
Explanation
With plain lifecycleScope.launch, Flow collection continues until the Activity is permanently destroyed (onDestroy). This means the app in the background will keep processing location or network updates and consuming memory. repeatOnLifecycle(Lifecycle.State.STARTED) guarantees that consumption is suspended and cancelled as soon as the screen becomes invisible to the user.
Code example
viewLifecycleOwner.lifecycleScope.launch {
viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.articles.collect { articles ->
adapter.submitList(articles)
}
}
}Common mistakes
- Collecting a Flow inside plain lifecycleScope.launch without repeatOnLifecycle and assuming it stops automatically in the background.