Created
December 11, 2024 17:22
-
-
Save jubishop/efb1fe1a6e56f444c6d0ebf20cb0c739 to your computer and use it in GitHub Desktop.
generic swift status AVPlayer
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
protocol StatusObservable: NSObject, Sendable { | |
associatedtype Status: Equatable, Sendable | |
var status: Status { get } | |
var error: Error? { get } | |
} | |
extension AVPlayer: @retroactive Sendable {} | |
extension AVPlayer: StatusObservable { | |
typealias Status = AVPlayer.Status | |
} | |
extension AVPlayerItem: @retroactive Sendable {} | |
extension AVPlayerItem: StatusObservable { | |
typealias Status = AVPlayerItem.Status | |
} | |
// Then the function generic utilizing these protocols: | |
func addStatusObserver<T: StatusObservable>( | |
for observable: T, | |
failedStatus: T.Status | |
) { | |
keyValueObservers.append( | |
observable.observe( | |
\.status, | |
options: [.initial, .new] | |
) { [unowned self] _, change in | |
if change.newValue == failedStatus { | |
Task { await self.reset(from: observable.error) } | |
} | |
} | |
) | |
} | |
// And the call sites | |
addStatusObserver( | |
for: avPlayer, | |
failedStatus: .failed | |
) | |
addStatusObserver( | |
for: avPlayerItem, | |
failedStatus: .failed | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment