sindresorhus / Defaults

💾 Swifty and modern UserDefaults
https://swiftpackageindex.com/sindresorhus/Defaults/documentation/defaults
MIT License
1.97k stars 117 forks source link

Functions will be called immediately after adding observers #86

Closed RoyRao2333 closed 2 years ago

RoyRao2333 commented 2 years ago

Here's the thing: I recently discovered that when I add an observer to a key, the callback will be invoked immediately. Details as below in my ViewController:

image

My func didResetJCState(_:) will be called whenever the view is presented. Actually, I just want this function to be called only .sessionURL is changed. I don't know if this is a feature of your framework or anything...

Any advice would be great! :)

sindresorhus commented 2 years ago

That is the documented behavior: https://github.com/sindresorhus/Defaults#defaultsobserve

You can use Defaults.observe(.sessionURL, options: [.new]) if you don't want this.

RoyRao2333 commented 2 years ago

That is the documented behavior: https://github.com/sindresorhus/Defaults#defaultsobserve

You can use Defaults.observe(.sessionURL, options: [.new]) if you don't want this.

Sorry to bother you again but I found that there's no .new in options:

image

Any ideas? 😓

sindresorhus commented 2 years ago

Ah, yeah. My mistake, should be:

Defaults.observe(.sessionURL, options: [])
RoyRao2333 commented 2 years ago

Ah, yeah. My mistake, should be:

Defaults.observe(.sessionURL, options: [])

Thanks! That works perfectly!

RoyRao2333 commented 2 years ago

@sindresorhus And I would like to know that if I reassign a myValue to Defaults[.myValue] which they are identical (for example, myValue and Defaults[.myValue] are both equal to 100), could this trigger the callback in Defaults.observe? (My purpose is to trigger the callback whenever I reassign the value, whether they are equal or not)

Thanks!

sindresorhus commented 2 years ago

Yes, there's no deduplication going on. It will trigger for every assignment.

RoyRao2333 commented 2 years ago

Yes, there's no deduplication going on. It will trigger for every assignment.

Thank you so much for your time!