An advanced Ethereum/EVM mobile wallet
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
alpha-wallet-ios/AlphaWallet/Foundation/Subscribable.swift

57 lines
1.4 KiB

7 years ago
// Copyright SIX DAY LLC. All rights reserved.
import Foundation
//TODO probably should have an ID which is really good for debugging
7 years ago
open class Subscribable<T> {
public struct SubscribableKey: Hashable {
let id = UUID()
}
7 years ago
private var _value: T?
private var _subscribers: [SubscribableKey: (T?) -> Void] = .init()
private var _oneTimeSubscribers: [(T) -> Void] = []
7 years ago
open var value: T? {
get {
return _value
}
set {
_value = newValue
for f in _subscribers.values {
7 years ago
f(value)
}
if let value = value {
for f in _oneTimeSubscribers {
f(value)
}
_oneTimeSubscribers = []
}
7 years ago
}
}
public init(_ value: T?) {
_value = value
}
@discardableResult open func subscribe(_ subscribe: @escaping (T?) -> Void) -> SubscribableKey {
7 years ago
if let value = _value {
subscribe(value)
}
let key = SubscribableKey()
_subscribers[key] = subscribe
return key
7 years ago
}
open func subscribeOnce(_ subscribe: @escaping (T) -> Void) {
if let value = _value {
subscribe(value)
} else {
_oneTimeSubscribers.append(subscribe)
}
}
func unsubscribe(_ key: SubscribableKey) {
_subscribers.removeValue(forKey: key)
}
7 years ago
}