Is following a good idea, or could the coroutine r...
# compose
p
Is following a good idea, or could the coroutine run even in the background?
Copy code
LaunchedEffect(Unit) {
    while (true) {
        delay(30.seconds)
        println("update")
    }
}
m
It is fine.
delay
will check for cancellation internally, and if it was already cancelled, it will terminate the
while
loop. (i.e when this composable leaves the composition)
👍 1
c
That will work fine as long as the Composable remains in view. If the view goes away, that loop will terminate. If you want it to actually run in the background, you will want to move it to a ViewModel and launch it in
viewModelScope
, or else create another CoroutineScope to launch it in, such as scoped to the Activity or Application
plus one 1
👍 1
p
No, I would like to avoid running it background. I have some excessive power consumption issues, and I was wondering this is the cause for it.
c
Coroutines started by
LaunchedEffect
are managed properly by Compose and won’t get orphaned, and Coroutines consume almost no resources while suspended, unlike Threads. So I’m guessing this probably isn’t what’s causing the problem for you.
p
Ok, thanks guys!
👌 1
e
In the past I've seen some weird behavior with code like this and backgrounding, specifically that it would continue to run unless it was wrapped in a
launch
. If you run that code, what happens?
p
I've tried it, and code from my example is also running, when I minimize the app. Same if I use
launch()
I guess proper way is using
lifecycle.repeatOnLifecycle { launch { ... } }
c
Yes, the Compose Views may still be active when the app itself goes into the background. If you want to pause the coroutines fully, you’ll need to add in the lifecycle-aware coroutines components