Skip to content

Commit d32483d

Browse files
committed
Model store minimize amount of locking needed
Only lock when reading and writing from the dictionary, to minimize amount of locking when unnecessary
1 parent 9412cf6 commit d32483d

File tree

1 file changed

+24
-23
lines changed

1 file changed

+24
-23
lines changed

iOS_SDK/OneSignalSDK/OneSignalOSCore/Source/OSModelStore.swift

+24-23
Original file line numberDiff line numberDiff line change
@@ -105,14 +105,12 @@ open class OSModelStore<TModel: OSModel>: NSObject {
105105

106106
// listen for changes to this model
107107
model.changeNotifier.subscribe(self)
108-
109-
guard !hydrating else {
110-
return
111-
}
112-
113-
self.changeSubscription.fire { modelStoreListener in
114-
modelStoreListener.onAdded(model)
115-
}
108+
}
109+
guard !hydrating else {
110+
return
111+
}
112+
self.changeSubscription.fire { modelStoreListener in
113+
modelStoreListener.onAdded(model)
116114
}
117115
}
118116

@@ -121,24 +119,28 @@ open class OSModelStore<TModel: OSModel>: NSObject {
121119
This can happen if remove email or SMS is called and it doesn't exist in the store.
122120
*/
123121
public func remove(_ id: String) {
122+
var model: TModel?
124123
lock.withLock {
125124
OneSignalLog.onesignalLog(.LL_VERBOSE, message: "OSModelStore remove() called with model \(id)")
126-
if let model = models[id] {
125+
if let foundModel = models[id] {
126+
model = foundModel
127127
models.removeValue(forKey: id)
128128

129129
// persist the models (with removed model) to storage
130130
OneSignalUserDefaults.initShared().saveCodeableData(forKey: self.storeKey, withValue: self.models)
131-
132-
// no longer listen for changes to this model
133-
model.changeNotifier.unsubscribe(self)
134-
135-
self.changeSubscription.fire { modelStoreListener in
136-
modelStoreListener.onRemoved(model)
137-
}
138131
} else {
139132
OneSignalLog.onesignalLog(.LL_ERROR, message: "OSModelStore cannot remove \(id) because it doesn't exist in the store.")
133+
return
140134
}
141135
}
136+
guard let model = model else {
137+
return
138+
}
139+
// no longer listen for changes to this model
140+
model.changeNotifier.unsubscribe(self)
141+
self.changeSubscription.fire { modelStoreListener in
142+
modelStoreListener.onRemoved(model)
143+
}
142144
}
143145

144146
/**
@@ -167,13 +169,12 @@ extension OSModelStore: OSModelChangedHandler {
167169
// persist the changed models to storage
168170
lock.withLock {
169171
OneSignalUserDefaults.initShared().saveCodeableData(forKey: self.storeKey, withValue: self.models)
170-
171-
guard !hydrating else {
172-
return
173-
}
174-
self.changeSubscription.fire { modelStoreListener in
175-
modelStoreListener.onUpdated(args)
176-
}
172+
}
173+
guard !hydrating else {
174+
return
175+
}
176+
self.changeSubscription.fire { modelStoreListener in
177+
modelStoreListener.onUpdated(args)
177178
}
178179
}
179180
}

0 commit comments

Comments
 (0)