Created
April 23, 2018 16:41
-
-
Save jayrhynas/793586e946ff160925d22ca74a8d67d1 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
class ObservationToken { | |
let cancellationClosure: (ObservationToken) -> Void | |
init(cancellationClosure: @escaping (ObservationToken) -> Void) { | |
self.cancellationClosure = cancellationClosure | |
} | |
func cancel() { | |
cancellationClosure(self) | |
} | |
} | |
class AudioPlayer { | |
var observations = [ObjectIdentifier: (AudioPlayer, Item) -> Void]() | |
@discardableResult | |
func addObserver<T: AnyObject>( | |
_ observer: T, | |
closure: @escaping (T, AudioPlayer, Item) -> Void | |
) -> ObservationToken { | |
let token = ObservationToken { [weak self] token in | |
self?.observations.removeValue(forKey: ObjectIdentifier(token)) | |
} | |
let id = ObjectIdentifier(token) | |
observations[id] = { [weak self, weak observer] player, item in | |
guard let observer = observer else { | |
self?.observations.removeValue(forKey: id) | |
return | |
} | |
closure(observer, player, item) | |
} | |
return token | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment