I want to react every time the application state changes. I’m listening to the .applicationState
publisher:
UIApplication.shared.publisher(for: .applicationState)
.subscribe(on: DispatchQueue.main)
.sink(receiveCompletion: { completion in
switch completion {
case .finished:
print("finished")
case .failure:
print("failure")
}
}, receiveValue: { state in
print("state", state.rawValue)
})
.store(in: &cancellables)
However, this only fires once (but doesn’t complete). If I background the app and reopen it, it doesn’t publish any new values. Why?
2
Answers
The publisher you are using is for KVO-compliant properties. (See Performing Key-Value Observing with Combine.) But the archived Key-Value Observing Programming Guide warns us:
But the notification center can inform us of these state changes, e.g.,
didBecomeActiveNotification
:Or, just:
See Routing Notifications to Combine Subscribers. See Using Key-Value Observing in Swift for information about creating your own KVO-compliant types in Swift.
It looks applicationstate like is not ‘KVO-compliant’. Which means you can’t use KVO to observe the property.
NSObject.publisher(for:)
is managed by KVOTo read the applicationState from single Publisher you can use multiple Notification about UI-Lifecycle like bleow.