forked from shadowfacts/Tusker
Use KVO to invalidate LazilyDecoding properties
This commit is contained in:
parent
cacc8a51cc
commit
df7b62e14b
|
@ -11,13 +11,13 @@ import Foundation
|
|||
private let decoder = PropertyListDecoder()
|
||||
private let encoder = PropertyListEncoder()
|
||||
|
||||
// todo: invalidate cache on underlying data change using KVO?
|
||||
@propertyWrapper
|
||||
public struct LazilyDecoding<Enclosing, Value: Codable> {
|
||||
public struct LazilyDecoding<Enclosing: NSObject, Value: Codable> {
|
||||
|
||||
private let keyPath: ReferenceWritableKeyPath<Enclosing, Data?>
|
||||
private let fallback: Value
|
||||
private var value: Value?
|
||||
private var observation: NSKeyValueObservation?
|
||||
|
||||
init(from keyPath: ReferenceWritableKeyPath<Enclosing, Data?>, fallback: Value) {
|
||||
self.keyPath = keyPath
|
||||
|
@ -39,6 +39,12 @@ public struct LazilyDecoding<Enclosing, Value: Codable> {
|
|||
do {
|
||||
let value = try decoder.decode(Box<Value>.self, from: data)
|
||||
wrapper.value = value.value
|
||||
wrapper.observation = instance.observe(wrapper.keyPath, changeHandler: { instance, _ in
|
||||
var updated = instance[keyPath: storageKeyPath]
|
||||
updated.value = nil
|
||||
updated.observation = nil
|
||||
instance[keyPath: storageKeyPath] = updated
|
||||
})
|
||||
instance[keyPath: storageKeyPath] = wrapper
|
||||
return value.value
|
||||
} catch {
|
||||
|
|
Loading…
Reference in New Issue