Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ios-background-execution] Add wrapper for iOS background tasks #48

Merged
merged 1 commit into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
package ch.dreipol.dreimultiplatform.coroutines

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

actual fun CoroutineScope.launchBackgroundTask(block: suspend CoroutineScope.() -> Unit) : Job = launch(block = block)
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package ch.dreipol.dreimultiplatform.coroutines

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job

/** A task that continues running while the app is in the background on iOS.
*/
expect fun CoroutineScope.launchBackgroundTask(block: suspend CoroutineScope.() -> Unit) : Job
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package ch.dreipol.dreimultiplatform.coroutines

import co.touchlab.kermit.Logger
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.InternalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.cancel
import kotlinx.coroutines.launch
import platform.UIKit.UIApplication

actual fun CoroutineScope.launchBackgroundTask(block: suspend CoroutineScope.() -> Unit) : Job = BackgroundTask(launch(block = block))

private class BackgroundTask(val underlyingJob: Job) : Job by underlyingJob {
private val backgroundTaskIdentifier = UIApplication.sharedApplication.beginBackgroundTaskWithExpirationHandler {
Logger.w { "Cancelling long running background task!" }
underlyingJob.cancel("Background Task is about to expire!")
}

@OptIn(InternalCoroutinesApi::class)
private val completionHandle = underlyingJob.invokeOnCompletion(onCancelling = true) {
UIApplication.sharedApplication.endBackgroundTask(backgroundTaskIdentifier)
}
}