A flow is collected in lifecycleScope without repeatOnLifecycle, so it keeps running while the screen is stopped
What it finds
lifecycleScope of an activity or fragment is cancelled only when it is destroyed. A flow collected in a coroutine launched there keeps running while the screen is in the background, doing work nobody sees, and in a fragment it touches views after onDestroyView has dropped them. repeatOnLifecycle or flowWithLifecycle stop the collection when the screen stops and start it again when it returns.
Reported for collect, collectLatest and collectIndexed in the lambda of lifecycleScope.launch (through lambdas that run in place) in a class that extends an activity or a fragment, and for launchIn(lifecycleScope), when neither repeatOnLifecycle nor flowWithLifecycle is in the way. Files that import nothing from androidx.lifecycle are left alone.
From the rule's source, flow_without_lifecycle.rs.
import androidx.lifecycle.lifecycleScopeimport androidx.lifecycle.repeatOnLifecycle class ProfileFragment : Fragment() { override fun onViewCreated(view: View, savedInstanceState: Bundle?) { viewLifecycleOwner.lifecycleScope.launch { viewModel.state.collect { render(it) }tx0 reports: the flow is collected in lifecycleScope and keeps running while the screen is stopped } lifecycleScope.launch { launch { viewModel.events.collectLatest { show(it) } }tx0 reports: keeps running while the screen is stopped } viewModel.state.onEach { render(it) }.launchIn(viewLifecycleOwner.lifecycleScope)tx0 reports: launchIn(lifecycleScope) keeps collecting viewLifecycleOwner.lifecycleScope.launch { viewLifecycleOwner.repeatOnLifecycle(Lifecycle.State.STARTED) { viewModel.state.collect { render(it) } } } viewModel.state.flowWithLifecycle(lifecycle).onEach { render(it) }.launchIn(lifecycleScope) lifecycleScope.launch { val first = viewModel.state.first() render(first) } lifecycleScope.launch { button.setOnClickListener { scope.launch { other.collect { } } } } }} class Repository(private val scope: CoroutineScope) { fun start() { scope.launch { source.collect { save(it) } } }} Turn it on, off or suppress it
The rule runs from the strict tier up. To turn it on in a lower tier, give it a level in tx0.toml:
[rules]
"tx0/kotlin:flow-collected-without-lifecycle" = "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:flow-collected-without-lifecycle] reason="..."tx0 explain tx0/kotlin:flow-collected-without-lifecycle shows the same in the terminal. Found a false positive? Report it.