sunshinejr / SwiftyUserDefaults

Modern Swift API for NSUserDefaults
http://radex.io/swift/nsuserdefaults/static
MIT License
4.86k stars 367 forks source link

Observe not work. #271

Closed Horse888 closed 3 years ago

Horse888 commented 3 years ago
extension DefaultsKeys {
    var username: DefaultsKey<String?> { return .init("UserName") }
}

then

Defaults.observe(\.username) { update in
                print(update)
            }

Defaults.username = "A"

Observe not work, nothing print out.

sunshinejr commented 3 years ago

Hey @Horse888, can you try to hold the reference for the observing token and see if it helps? e.g.

final class Test {
    var observer: DefaultsDisposable?

    func doSomething() {
        observer = Defaults.observe(\.username) { update in
            print(update)
        }

        Defaults.username = "A"
    }
}
Horse888 commented 3 years ago
var observer: DefaultsDisposable?

Dear @sunshinejr , I tried it with luck. Thanks. But I found that if I can't access the value in the update block. e.g.

final class Test {
    var observer: DefaultsDisposable?

    func doSomething() {
        observer = Defaults.observe(\.username) { update in
            print(update)
            print(Defaults.username) // example 1: Can't access, crash
            NotificationCenter.default.post(name: NOTIFICATION_NAME, object: nil) // example 2: I want to infer app the 'username' updated. App can't access 'username' either in this time.
        }

        Defaults.username = "A"
    }
}
sunshinejr commented 3 years ago

@Horse888 yeah I think this is a known bug, didn't have a chance to look at it yet. But you should have the new value in the update var, don't you?

Horse888 commented 3 years ago

@Horse888 yeah I think this is a known bug, didn't have a chance to look at it yet. But you should have the new value in the update var, don't you?

Yes, I can get the new value. Hope it will be fixed in future. Thanks!

sunshinejr commented 3 years ago

@Horse888 just FYI, the fix for this was released in 5.2.0. Going to close this issue but lemme know if there is anything else I can help with!