What is the lifecycle of the `CoroutineScope` used...
# compose
e
What is the lifecycle of the
CoroutineScope
used by
LaunchedEffect
? If I run the following, then the logs get printed even after my Activity stops:
Copy code
LaunchedEffect(Unit) {
  while(true) {
    Log.e("TEST", System.currentTimeMillis().toString)
    delay(1_000)
  }
}
t
I wonder if this needs to be checking
isActive
otherwise this coroutine won’t support cancellation?
Copy code
LaunchedEffect(Unit) {
  while(isActive) {
    Log.e("TEST", System.currentTimeMillis().toString)
    delay(1_000)
  }
}
e
I think the
delay
would handle cancellation
s
It will, but always a good idea to do that instead of true so that if the code gets refactored in the future and the delay is removed, it's still supporting cancellation. With that said, if you need the coroutine to follow the lifecycle, maybe you can try using the
repeatOnLifecycle
API inside there? You can fetch the lifecycle outside of the LaunchedEffect using the composition local of lifecycle
e
This is contrived code. I'm just curious about what scope it uses (and I had a fruitless search through the source)
s
Probably starts the coroutine after the first successful composition is applied, and ends when this composable leaves the slot table. Aka it will live in the background too without using repeatOnLifecycle
e
And it doesn't leave the slot table until the ComposeView is destroyed?
s
This is still me guessing, not on a computer to check right now, but I'd probably say yes
e
Ok thanks! Now I need to figure out how it was still running in the background. I thought Android stopped background processing after a while, but this went on for almost 20 minutes straight.
s
Yeah modern phones have the capacity to run the app for a pretty long time afaik without killing it if you're not opening a lot of new apps. I don't think this is odd tbh