In my application, i send request to an API using coroutine, and flow. When the request comes, i changed the value of stateFlow so that the collector in my activity see that and does its job. That's a simple scenario. In the android website ( https://developer.android.com/kotlin/flow/stateflow-and-sharedflow ), 2 approach is suggested. In this case, which approach i should prefer ?
The following is a quotation from the above link. :
StateFlows are safe to collect using the launchWhen() functions since they're scoped to ViewModels, making them remain in memory when the View goes to the background, and they do lightweight work by just notifying the View about UI states. However, the problem might come with other producers that do more intensive work.
In this quotation, it is said 1st approach is safe however, in the last sentence there is a warning. What's that warning for ? I didn't understand whether it is safe or not. Does producers continue to work in first approach? In my case, if request does not come yet, and user goes the app in background, does producers work and try to update UI ?
1st approach :
class LatestNewsActivity : AppCompatActivity() {
private val latestNewsViewModel = // getViewModel()
override fun onCreate(savedInstanceState: Bundle?) {
...
// This coroutine will run the given block when the lifecycle
// is at least in the Started state and will suspend when
// the view moves to the Stopped state
lifecycleScope.launchWhenStarted {
// Triggers the flow and starts listening for values
latestNewsViewModel.uiState.collect { uiState ->
// New value received
when (uiState) {
is LatestNewsUiState.Success -> showFavoriteNews(uiState.news)
is LatestNewsUiState.Error -> showError(uiState.exception)
}
}
}
}
}
2nd approach :
class LatestNewsActivity : AppCompatActivity() {
...
// 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()
}
}
Which approach is more suitable in this very simple case ?