This is how I did it in a class, not in a view:
var queueObserver: AnyCancellable?
let musicPlayer = ApplicationMusicPlayer.shared
if queueObserver == nil {
queueObserver = musicPlayer.queue.objectWillChange
.sink { [weak self] in
self?.queueDidChange()
}
}
return musicPlayer
}
private func queueDidChange() {
// When we get this event, the song hasn't actually changed yet so we try a little later.
DispatchQueue.main.asyncAfter(deadline: .now() + 2.0, execute: {
NowPlaying.shared.setSong(self.musicPlayer.queue.currentEntry?.title ?? "Unknown")
})
}