In the Android official documentation, it says the following about StateFlow vs Livedata:
LiveData.observe() automatically unregisters the consumer when the view goes to the STOPPED state, whereas collecting from a StateFlow or any other flow does not.
and they recommend to cancel eacy flow collection like this:
// Coroutine listening for UI states
private var uiStateJob: Job? = null
override fun onStart() {
super.onStart()
// Start collecting when the View is visible
uiStateJob = lifecycleScope.launch {
latestNewsViewModel.uiState.collect { uiState -> ... }
}
}
override fun onStop() {
// Stop collecting when the View goes to the background
uiStateJob?.cancel()
super.onStop()
}
As far as I know about structured concurrency, when we cancel the parent job, all children jobs are cancelled automatically and flow terminal operator collect should not be an exception. In this case, we are using lifecycleScope that should cancel when the lifecycleOwner is destroyed. Then, why do we need to manually cancel flow collection in this case? what am I missing here?