package eu.friedcutlet.yokan.services.scheduling import eu.friedcutlet.yokan.services.catchingNonCancellation import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch /** Completes even when expiry cancels a callback before dispatch, and only after its cleanup joins. */ internal fun launchCompletingBackgroundTask( scope: CoroutineScope, run: suspend () -> ProfileWorkResult, complete: (Boolean) -> Unit, ): Job { val succeeded = MutableStateFlow(false) val job = scope.launch { val outcome = catchingNonCancellation { run() }.getOrNull() succeeded.update { outcome?.shouldRetry == false } } job.invokeOnCompletion { cause -> complete(cause == null && succeeded.value) } return job }