launchWhenStarted and its kind pause a coroutine instead of cancelling it

tx0/kotlin:lifecycle-launch-whenrecommendedwarningframeworks/androiddepth fastbug, android

What it finds

lifecycleScope.launchWhenStarted { flow.collect { ... } } suspends the coroutine while the lifecycle is below the state, but keeps the flow's producer running, so work and resources go on in the background. The Android lifecycle library deprecates these functions in favor of repeatOnLifecycle, which cancels and restarts the work.

From the rule's source, deprecated_lifecycle_launch.rs.

Example from the rule's tests
class Screen : Fragment() {    override fun onStart() {        lifecycleScope.launchWhenStarted {tx0 reports: launchWhenStarted keeps the work running            model.state.collect { render(it) }        }        lifecycleScope.launch {            repeatOnLifecycle(Lifecycle.State.STARTED) { model.state.collect { render(it) } }        }    }}
Highlighted lines are the ones tx0 reports, with its message under each; the other lines are left alone.

Turn it on, off or suppress it

The rule runs from the recommended tier up. To turn it on in a lower tier, give it a level in tx0.toml:

tx0.toml
[rules]
"tx0/kotlin:lifecycle-launch-when" = "warning"

To keep one finding, suppress it with a reason. tx0 suppress ID --reason "..." writes the comment on the line before the code:

// tx0: ignore[tx0/kotlin:lifecycle-launch-when] reason="..."

tx0 explain tx0/kotlin:lifecycle-launch-when shows the same in the terminal. Found a false positive? Report it.