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

Avoid blocking main thread for backupCache calls when leaving app #187

Merged
merged 2 commits into from
Oct 2, 2024
Merged
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
31 changes: 29 additions & 2 deletions Sources/TelemetryDeck/Signals/SignalManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -147,9 +147,23 @@ final class SignalManager: SignalManageable, @unchecked Sendable {
// MARK: - Notifications

private extension SignalManager {
@MainActor
@objc func appWillTerminate() {
configuration.logHandler?.log(.debug, message: #function)
signalCache.backupCache()

#if os(watchOS) || os(macOS)
self.signalCache.backupCache()
#else
// run backup in background task to avoid blocking main thread while ensuring app stays open during write
let backgroundTaskID = UIApplication.shared.beginBackgroundTask()
DispatchQueue.global(qos: .background).async {
self.signalCache.backupCache()

DispatchQueue.main.async {
UIApplication.shared.endBackgroundTask(backgroundTaskID)
}
}
#endif
}

/// WatchOS doesn't have a notification before it's killed, so we have to use background/foreground
Expand All @@ -168,13 +182,26 @@ private extension SignalManager {
sendCachedSignalsRepeatedly()
}

@MainActor
@objc func didEnterBackground() {
configuration.logHandler?.log(.debug, message: #function)

sendTimer?.invalidate()
sendTimer = nil

signalCache.backupCache()
#if os(watchOS) || os(macOS)
self.signalCache.backupCache()
#else
// run backup in background task to avoid blocking main thread while ensuring app stays open during write
let backgroundTaskID = UIApplication.shared.beginBackgroundTask()
DispatchQueue.global(qos: .background).async {
self.signalCache.backupCache()

DispatchQueue.main.async {
UIApplication.shared.endBackgroundTask(backgroundTaskID)
}
}
#endif
}
#endif
}
Expand Down