forked from hyperoslo/Cache
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
364d2ec
commit 5e53be9
Showing
3 changed files
with
49 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,38 @@ | ||
import Foundation | ||
|
||
public enum KeyChange<T> { | ||
case edit(before: T?, after: T?) | ||
case remove | ||
} | ||
|
||
public final class KeyObservationRegistry<Storage: StorageAware> { | ||
public typealias Observation = (Storage, KeyChange<Storage.T>) -> Void | ||
private(set) var observations = [String: Observation]() | ||
|
||
@discardableResult | ||
public func addObservation(_ observation: @escaping Observation, forKey key: String) -> ObservationToken { | ||
observations[key] = observation | ||
|
||
return ObservationToken { [weak self] in | ||
self?.observations.removeValue(forKey: key) | ||
} | ||
} | ||
|
||
public func removeObservation(forKey key: String) { | ||
observations.removeValue(forKey: key) | ||
} | ||
|
||
public func removeObservation(token: ObservationToken) { | ||
token.cancel() | ||
} | ||
|
||
public func removeAllObservations() { | ||
observations.removeAll() | ||
} | ||
|
||
func notifyObservers(about change: KeyChange<Storage.T>, in storage: Storage) { | ||
observations.values.forEach { closure in | ||
closure(storage, change) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters