Created
July 16, 2018 18:05
-
-
Save jayrhynas/727a8cd36923713dac9e3c088276b722 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
import Foundation | |
class KVObserver: NSObject { | |
let subject: NSObject | |
let keyPath: String | |
let block: (Any?) -> Void | |
init(subject: NSObject, keyPath: String, block: @escaping (Any?) -> Void) { | |
self.subject = subject | |
self.keyPath = keyPath | |
self.block = block | |
super.init() | |
subject.addObserver(self, forKeyPath: keyPath, options: [], context: nil) | |
} | |
deinit { | |
subject.removeObserver(self, forKeyPath: self.keyPath) | |
} | |
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { | |
guard keyPath == self.keyPath else { return } | |
self.block(object) | |
} | |
} |
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
import Foundation | |
protocol TrackProvider { | |
var track: Track? { get } | |
func observeTrack(_ block: @escaping (TrackProvider) -> Void) -> KVObserver | |
} | |
extension TrackProvider where Self: NSObject { | |
func observeTrack(_ block: @escaping (TrackProvider) -> Void) -> KVObserver { | |
return KVObserver(subject: self, keyPath: "track", block: { obj in | |
guard let provider = obj as? TrackProvider else { return } | |
block(provider) | |
}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment