Skip to content

Commit

Permalink
Merge pull request #48 from dreipol/feature/ios-background-execution
Browse files Browse the repository at this point in the history
[ios-background-execution] Add wrapper for iOS background tasks
  • Loading branch information
melbic authored Apr 23, 2024
2 parents ecac6b9 + c58654d commit 9eb5e37
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 0 deletions.
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)
}
}

0 comments on commit 9eb5e37

Please sign in to comment.