-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathKeyedSubscriptionStore.swift
44 lines (34 loc) · 1.36 KB
/
KeyedSubscriptionStore.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import Combine
import Synchronized
public extension Cancellable {
func store(in store: KeyedSubscriptionStore, key: String) {
store.store(subscription: AnyCancellable(self), forKey: key)
}
}
public final class KeyedSubscriptionStore: Hashable {
private var subscriptions: [String: AnyCancellable]
private let lock = Lock()
public init(subscriptions: [String: AnyCancellable] = [:]) {
self.subscriptions = subscriptions
}
public var isEmpty: Bool { lock.locked { subscriptions.isEmpty } }
public func containsSubscription(forKey key: String) -> Bool {
lock.locked { subscriptions[key] != nil }
}
public func store(subscription: AnyCancellable, forKey key: String) {
lock.locked { subscriptions[key] = subscription }
}
public func removeAll(keepingCapacity keepCapacity: Bool = false) {
lock.locked { subscriptions.removeAll(keepingCapacity: keepCapacity) }
}
@discardableResult
public func removeSubscription(forKey key: String) -> AnyCancellable? {
lock.locked { subscriptions.removeValue(forKey: key) }
}
public func hash(into hasher: inout Hasher) {
hasher.combine(ObjectIdentifier(self))
}
public static func == (lhs: KeyedSubscriptionStore, rhs: KeyedSubscriptionStore) -> Bool {
ObjectIdentifier(lhs) == ObjectIdentifier(rhs)
}
}