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 decoder = PropertyListDecoder()
|
||||||
private let encoder = PropertyListEncoder()
|
private let encoder = PropertyListEncoder()
|
||||||
|
|
||||||
// todo: invalidate cache on underlying data change using KVO?
|
|
||||||
@propertyWrapper
|
@propertyWrapper
|
||||||
public struct LazilyDecoding<Enclosing, Value: Codable> {
|
public struct LazilyDecoding<Enclosing: NSObject, Value: Codable> {
|
||||||
|
|
||||||
private let keyPath: ReferenceWritableKeyPath<Enclosing, Data?>
|
private let keyPath: ReferenceWritableKeyPath<Enclosing, Data?>
|
||||||
private let fallback: Value
|
private let fallback: Value
|
||||||
private var value: Value?
|
private var value: Value?
|
||||||
|
private var observation: NSKeyValueObservation?
|
||||||
|
|
||||||
init(from keyPath: ReferenceWritableKeyPath<Enclosing, Data?>, fallback: Value) {
|
init(from keyPath: ReferenceWritableKeyPath<Enclosing, Data?>, fallback: Value) {
|
||||||
self.keyPath = keyPath
|
self.keyPath = keyPath
|
||||||
|
@ -39,6 +39,12 @@ public struct LazilyDecoding<Enclosing, Value: Codable> {
|
||||||
do {
|
do {
|
||||||
let value = try decoder.decode(Box<Value>.self, from: data)
|
let value = try decoder.decode(Box<Value>.self, from: data)
|
||||||
wrapper.value = value.value
|
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
|
instance[keyPath: storageKeyPath] = wrapper
|
||||||
return value.value
|
return value.value
|
||||||
} catch {
|
} catch {
|
||||||
|
|
Loading…
Reference in New Issue