diff --git a/Tusker/LazilyDecoding.swift b/Tusker/LazilyDecoding.swift index c77eed6b..542f1d3c 100644 --- a/Tusker/LazilyDecoding.swift +++ b/Tusker/LazilyDecoding.swift @@ -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 { +public struct LazilyDecoding { private let keyPath: ReferenceWritableKeyPath private let fallback: Value private var value: Value? + private var observation: NSKeyValueObservation? init(from keyPath: ReferenceWritableKeyPath, fallback: Value) { self.keyPath = keyPath @@ -39,6 +39,12 @@ public struct LazilyDecoding { do { let value = try decoder.decode(Box.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 {