Skip to content

Save to file storage when app is about to be terminated #2992

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

Merged
merged 2 commits into from
Apr 15, 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
15 changes: 13 additions & 2 deletions Sources/ComposableArchitecture/Internal/NotificationName.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public var willResignNotificationName: Notification.Name? {
}

@_spi(Internals)
public var willEnterForegroundNotificationName: Notification.Name? {
public let willEnterForegroundNotificationName: Notification.Name? = {
#if os(iOS) || os(tvOS) || os(visionOS)
return UIApplication.willEnterForegroundNotification
#elseif os(macOS)
Expand All @@ -38,7 +38,18 @@ public var willEnterForegroundNotificationName: Notification.Name? {
return nil
}
#endif
}
}()

@_spi(Internals)
public let willTerminateNotificationName: Notification.Name? = {
#if os(iOS) || os(tvOS) || os(visionOS)
return UIApplication.willTerminateNotification
#elseif os(macOS)
return NSApplication.willTerminateNotification
#else
return nil
#endif
}()

var canListenForResignActive: Bool {
willResignNotificationName != nil
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -300,16 +300,23 @@ extension AppStorageKey: PersistenceKey {
else { return }
didSet(self.store.value(forKey: self.key) as? Value ?? initialValue)
}
let willEnterForeground = NotificationCenter.default.addObserver(
forName: willEnterForegroundNotificationName,
object: nil,
queue: nil
) { _ in
didSet(self.store.value(forKey: self.key) as? Value ?? initialValue)
let willEnterForeground: (any NSObjectProtocol)?
if let willEnterForegroundNotificationName {
Comment on lines +303 to +304
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since these notification names are nil for platforms that don't support the notification we should unwrap them. Otherwise we subscribe to notifications with a nil name, which basically means subscribe to all notifications.

willEnterForeground = NotificationCenter.default.addObserver(
forName: willEnterForegroundNotificationName,
object: nil,
queue: nil
) { _ in
didSet(self.store.value(forKey: self.key) as? Value ?? initialValue)
}
} else {
willEnterForeground = nil
}
return Shared.Subscription {
NotificationCenter.default.removeObserver(userDefaultsDidChange)
NotificationCenter.default.removeObserver(willEnterForeground)
if let willEnterForeground {
NotificationCenter.default.removeObserver(willEnterForeground)
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,30 +81,56 @@ public final class FileStorageKey<Value: Codable & Sendable>: PersistenceKey, @u
didSet(self.load(initialValue: initialValue))
}
}
#if canImport(AppKit) || canImport(UIKit) || canImport(WatchKit)
let willResign = NotificationCenter.default.addObserver(
let willResign: (any NSObjectProtocol)?
if let willResignNotificationName {
willResign = NotificationCenter.default.addObserver(
forName: willResignNotificationName,
object: nil,
queue: nil
) { [weak self] _ in
guard
let self,
let workItem = self.workItem
guard let self
else { return }
self.storage.async(execute: workItem)
self.storage.async(
execute: DispatchWorkItem {
self.workItem?.cancel()
self.workItem = nil
}
)
performImmediately()
}
} else {
willResign = nil
}
let willTerminate: (any NSObjectProtocol)?
if let willTerminateNotificationName {
willTerminate = NotificationCenter.default.addObserver(
forName: willTerminateNotificationName,
object: nil,
queue: nil
) { [weak self] _ in
guard let self
else { return }
performImmediately()
}
#endif
} else {
willTerminate = nil
}
return Shared.Subscription {
cancellable.cancel()
NotificationCenter.default.removeObserver(willResign)
if let willResign {
NotificationCenter.default.removeObserver(willResign)
}
if let willTerminate {
NotificationCenter.default.removeObserver(willTerminate)
}
}
}

private func performImmediately() {
guard let workItem = self.workItem
else { return }
self.storage.async(execute: workItem)
self.storage.async(
execute: DispatchWorkItem {
self.workItem?.cancel()
self.workItem = nil
}
)
}
}

extension FileStorageKey: Hashable {
Expand Down
21 changes: 21 additions & 0 deletions Tests/ComposableArchitectureTests/FileStorageTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,7 @@ final class FileStorageTests: XCTestCase {

func testWillResign() throws {
guard let willResignNotificationName else { return }

let testScheduler = DispatchQueue.test
let fileStorage = InMemoryFileStorage(scheduler: testScheduler.eraseToAnyScheduler())
try withDependencies {
Expand All @@ -94,6 +95,26 @@ final class FileStorageTests: XCTestCase {
}
}

func testWillTerminate() throws {
guard let willTerminateNotificationName else { return }

let testScheduler = DispatchQueue.test
let fileStorage = InMemoryFileStorage(scheduler: testScheduler.eraseToAnyScheduler())
try withDependencies {
$0.defaultFileStorage = fileStorage
} operation: {
@Shared(.fileStorage(.fileURL)) var users = [User]()
XCTAssertNoDifference(fileStorage.fileSystem.value, [.fileURL: Data()])

users.append(.blob)
XCTAssertNoDifference(fileStorage.fileSystem.value, [.fileURL: Data()])

NotificationCenter.default.post(name: willTerminateNotificationName, object: nil)
testScheduler.advance()
try XCTAssertNoDifference(fileStorage.fileSystem.value.users(for: .fileURL), [.blob])
}
}

func testWillResignAndDebounce() async throws {
guard let willResignNotificationName else { return }
let testScheduler = DispatchQueue.test
Expand Down
Loading