I am aware that ApplicationMusicPlayer.shared.state is implemented as an observed object, but I'm wondering if it's possible to store that instance in a class annotated with ObservableObject so that I can use objectWillChance
or other properties and then forward the values and state I care about view @Published
properties. I'm thinking something like this:
class SomeViewModel: ObservableObject {
@Published var isPlaying: Bool = false
init() {
ApplicationMusicPlayer.shared.state.objectWillChange.sink { [self]
isPlaying = ApplicationMusicPlayer.shared.state.playbackStatus == .playing
}
}
}
If I create this class and stick in a SwiftUI View I can see the init
being called, but the objectWillChange
never seems to fire.
I can however do this and it seems to work inside of the SwiftUI View:
struct SomeView: View {
@ObservedObject private var playerState = ApplicationMusicPlayer.shared.state
@State private var isPlaying: Bool = false
var cancellableBag = Set<AnyCancellable>()
init() {
self.isPlaying = playerState.playbackStatus == .playing
playerState.objectWillChange.sink { [self] in
print(playerState.playbackStatus)
}.store(in: &cancellableBag)
}
}
interesting objectWillChange
fires twice for every state update, but I could deal with that if I could just use my own ObservableObject. I'd rather my music player not be so tightly coupled to the view I'm writing.