Colton Idle
05/15/2025, 4:55 PMLaunchedEffect(unitConnected) {
lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
while (true) {
delay(3_000)
if (!unitConnected) {
HardwareComponent.reconnect()
}
}
}
}
I'm mostly confused to how the above works because I would have thought that once it's backgrounded it would keep going and I'm confused at how it knows to stop the loop?Winson Chiu
05/15/2025, 4:57 PMWinson Chiu
05/15/2025, 4:58 PMColton Idle
05/15/2025, 5:00 PMrepeatOnLifecycle(Lifecycle.State.RESUMED) is a "scope"Wout Werkman
05/15/2025, 5:42 PMLaunchedEffect(unitConnected) {
if (!unitConnected) return@LaunchedEffect
// Now in the following code, you have the guarantee that this only runs while `unitIsConnected`
lifecycleOwner.lifecycle.repeatOnLifecycle(Lifecycle.State.RESUMED) {
while (true) {
delay(3.seconds)
HardwareComponent.reconnect()
}
}
}
Ideally Android would provide some useful flows for lifecycle state, but sadly they don't otherwise you could simply have done:
LaunchedEffect(unitConnected) {
if (!unitConnected) return@LaunchedEffect
// Now in the following code, you have the guarantee that this only runs while `unitIsConnected`
lifecycleOwner.lifeCycleFlowThatSadlyDoesNotExist().collectLatest { lifeCycleState ->
if (!lifeCycleState.meansThatAppIsOnForeground()) return@collectLatest
// Now in the following code, you have the guarantee that this only runs while the app is in foreground
while (true) {
delay(3.seconds)
HardwareComponent.reconnect() // Only runs while `unitIsConnected` and app is in foreground! Yay!
}
}
}Francesc
05/18/2025, 3:04 PMLifecycleEffect. There is also LifecycleResumeEffect and LIfecycleStartEffect for those 2 specific events.Colton Idle
05/18/2025, 3:51 PMFrancesc
05/18/2025, 5:43 PMFrancesc
05/18/2025, 5:49 PMWout Werkman
05/18/2025, 6:01 PMcancellation is cooperative in coroutines, so you would have to check for cancellation, could that be the issue?Many functions check for cancellation under the hood. Including
delay. So yes, in this case it's fineFrancesc
05/18/2025, 6:42 PMWout Werkman
05/18/2025, 6:54 PM