Skip to content

Commit 0d05a3e

Browse files
authored
Merge pull request #8 from 0xOpenBytes/feature/binding-action
Feature/binding action
2 parents fb0ee51 + 63ae2d6 commit 0d05a3e

File tree

2 files changed

+23
-16
lines changed

2 files changed

+23
-16
lines changed

Sources/CacheStore/Stores/CacheStore.swift

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,10 @@ public class CacheStore<Key: Hashable>: ObservableObject, Cacheable {
106106
cache[key] = nil
107107
lock.unlock()
108108
}
109+
110+
// MARK: - Copying
111+
112+
public func copy() -> CacheStore { CacheStore(initialValues: cache) }
109113
}
110114

111115
// MARK: -

Sources/CacheStore/Stores/Store.swift

Lines changed: 19 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,15 @@ public class Store<Key: Hashable, Action, Dependency>: ObservableObject, ActionH
6161
}
6262

6363
lock.lock()
64-
objectWillChange.send()
65-
actionHandler.handle(store: &store, action: action, dependency: dependency)
64+
65+
var storeCopy = store.copy()
66+
actionHandler.handle(store: &storeCopy, action: action, dependency: dependency)
67+
68+
if NSDictionary(dictionary: storeCopy.cache).isEqual(to: store.cache) == false {
69+
objectWillChange.send()
70+
store = storeCopy
71+
}
72+
6673
lock.unlock()
6774
}
6875

@@ -131,31 +138,27 @@ public class Store<Key: Hashable, Action, Dependency>: ObservableObject, ActionH
131138
)
132139
}
133140

134-
/// Creates a `Binding` for the given `Key`
141+
/// Creates a `Binding` for the given `Key` using an `Action` to set the value
135142
public func binding<Value>(
136143
_ key: Key,
137-
as: Value.Type = Value.self
144+
as: Value.Type = Value.self,
145+
using: @escaping (Value) -> Action
138146
) -> Binding<Value> {
139147
Binding(
140-
get: { self.store.resolve(key) },
141-
set: {
142-
self.objectWillChange.send()
143-
self.store.set(value: $0, forKey: key)
144-
}
148+
get: { self.resolve(key) },
149+
set: { self.handle(action: using($0)) }
145150
)
146151
}
147152

148-
/// Creates a `Binding` for the given `Key` where the value is Optional
153+
/// Creates a `Binding` for the given `Key`, where the value is Optional, using an `Action` to set the value
149154
public func optionalBinding<Value>(
150155
_ key: Key,
151-
as: Value.Type = Value.self
156+
as: Value.Type = Value.self,
157+
using: @escaping (Value?) -> Action
152158
) -> Binding<Value?> {
153159
Binding(
154-
get: { self.store.get(key) },
155-
set: {
156-
self.objectWillChange.send()
157-
self.store.set(value: $0, forKey: key)
158-
}
160+
get: { self.get(key) },
161+
set: { self.handle(action: using($0)) }
159162
)
160163
}
161164
}

0 commit comments

Comments
 (0)