Skip to content

Instantly share code, notes, and snippets.

@jayrhynas
Created April 23, 2018 16:41
Show Gist options
  • Save jayrhynas/793586e946ff160925d22ca74a8d67d1 to your computer and use it in GitHub Desktop.
Save jayrhynas/793586e946ff160925d22ca74a8d67d1 to your computer and use it in GitHub Desktop.
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