Created
          February 3, 2025 19:35 
        
      - 
      
- 
        Save tsabian/6eba01c0d7f957e76f425b4a47f4bfc2 to your computer and use it in GitHub Desktop. 
  
    
      This file contains hidden or 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
    
  
  
    
  | public final class MultiListenerBindable<T> { | |
| public typealias Handler = (T) -> Void | |
| public typealias TargetHandler<Target> = (Target, T) -> Void | |
| private var listeners: [UUID: Handler] = [:] | |
| public var value: T { | |
| didSet { | |
| notifyListeners() | |
| } | |
| } | |
| public init(_ value: T) { | |
| self.value = value | |
| } | |
| @discardableResult | |
| public func bind(listener: @escaping Handler) -> UUID { | |
| let id = UUID() | |
| listeners[id] = listener | |
| notifyListeners() | |
| return id | |
| } | |
| public func bind<Target: AnyObject>(to target: Target, | |
| listener: @escaping TargetHandler<Target>) -> UUID { | |
| let id = UUID() | |
| listeners[id] = { [weak target] value in | |
| guard let target else { return } | |
| listener(target, value) | |
| } | |
| notifyListeners() | |
| return id | |
| } | |
| public func unbind(id: UUID) { | |
| listeners.removeValue(forKey: id) | |
| } | |
| private func notifyListeners() { | |
| listeners.values.forEach { $0(value) } | |
| } | |
| } | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment