Handling app moving from foreground to background #1927
-
Hi TCA community, My app needs to do async cleanup work when it moves to background, e.g. flushing queued events, saving latest profile. Currently, I'm unable to explain the behavior I'm seeing in a barebones example repo I've set up when the app moves to TLDR:
I thought apps had around 5 seconds to do cleanup work, so am puzzled as to why the print gets frozen in a time machine until re-open. see also:
happy sunday 😃 |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Hey @andwrobs! In this simple case, you should probably fence your return .run { send in
let backgroundTaskID = await UIApplication.shared.beginBackgroundTask(withName: "\(Self.self)")
// Perform your work
try await mainQueue.sleep(for: .milliseconds(500))
await UIApplication.shared.endBackgroundTask(backgroundTaskID)
} This will grant you a little more execution time (around 30s AFAIK). There is a variant for extensions which can't touch Beware though, Ideally, this extension DependencyValues {
public var backgroundTask: BackgroundTask {
get { self[BackgroundTask.self] }
set { self[BackgroundTask.self] = newValue }
}
}
public struct BackgroundTask: Sendable {
public let begin: @Sendable @MainActor (String?) -> UIBackgroundTaskIdentifier
public let end: @Sendable @MainActor (UIBackgroundTaskIdentifier) -> Void
}
extension BackgroundTask: DependencyKey {
public static var liveValue: BackgroundTask {
.init {
UIApplication.shared.beginBackgroundTask(withName: $0)
} end: {
UIApplication.shared.endBackgroundTask($0)
}
}
public static var testValue: BackgroundTask {
.init(
begin: unimplemented(#"@Dependency(\.backgroundTask).begin"#),
end: unimplemented(#"@Dependency(\.backgroundTask).end"#)
)
}
public static var previewValue: BackgroundTask { liveValue }
} |
Beta Was this translation helpful? Give feedback.
Hey @andwrobs! In this simple case, you should probably fence your
.run
block with(begin|end)BackgroundTask
:This will grant you a little more execution time (around 30s AFAIK). There is a variant for extensions which can't touch
UIApplication.shared
. If you need more time, there are more complex background operation APIs, but this one should work.Beware though,
send
doesn't await for the effects produced by the emitted action t…