I want to collect flow when the lifecycle reaches specific state. So far I do it like this:
lifecycleScope.launchWhenStarted {
viewModel.someFlow
.onEach { /* it starts collecting flow in STARTED state and never stops */ }
.launchIn(this)
}
but this function is deprecated. Google recommends to replace it with repeatOnLifecycle(), but I don't want to repeat collecting flow every time I reach this state.
I found this link https://issuetracker.google.com/issues/270049505 and tried following solutions:
lifecycleScope.launch {
lifecycle.withStateAtLeast(Lifecycle.State.STARTED) {
...
}
}
lifecycleScope.launch {
lifecycle.withStarted {
...
}
}
I did such a test: I launch the application on a locked screen (and didn't unlock it yet). I expect a CREATED state, but the code inside these functions executes. I even myself "lifecycle.currentState" and it is in the state... STARTED. In the same scenario, the functions launchWhenStarted and repeatOnLifecycle(Lifecycle.State.STARTED) execute the code only when I unlock the screen. Do I not understand how these functions work or how the lifecycle works or are these functions bugged?