Please see the MRE below. Changing UserDefault suite to a custom one doesn't update the subscription beyond the first value.
public extension UserDefaults {
@objc dynamic var value1: Int {
get { integer(forKey: "value1") }
set { set(newValue, forKey: "value1") }
}
static var other: UserDefaults {
UserDefaults(suiteName: "other-defaults")!
}
}
struct ContentView: View {
private let sub = UserDefaults.other.publisher(for: \.value1).sink { print("SUB", $0) }
var body: some View {
Button("Add") {
UserDefaults.other.value1 += 1
debugPrint("SET", UserDefaults.other.value1)
}
.onReceive(UserDefaults.other.publisher(for: \.value1)) {
debugPrint("UI", $0)
}
}
}
Only the SwiftUI onReceive subscription is working.
SUB 0
"UI" 0
"SET" 1
"UI" 1
"SET" 2
"UI" 2
It works (though with multiple calls) if I set the standard UserDefaults suite.
struct ContentView2: View {
private let sub = UserDefaults.standard.publisher(for: \.value1).sink { print("SUB", $0) }
var body: some View {
Button("Add") {
UserDefaults.standard.value1 += 1
debugPrint("SET", UserDefaults.standard.value1)
}
.onReceive(UserDefaults.standard.publisher(for: \.value1)) {
debugPrint("UI", $0)
}
}
}
SUB 0
"UI" 0
SUB 1
SUB 1
"SET" 1
"UI" 1
"UI" 1
SUB 2
SUB 2
"SET" 2
"UI" 2
"UI" 2