0

I have a view that is connected to its own ObservableObject view model which references a nested websocket ObservableObject. However, whenever a new websocket message is received, the updated data isn't passed onto the view. Why doesn't it work and how can I fix it?

View

struct MainView: View {
    @StateObject var viewModel = MainViewModel()
    
    var body: some View {
        ZStack {
            ...
        }
        .onChange(of: viewModel.websocketViewModel.messageRcvd) { message in
            // this doesn't get triggered
            viewModel.messageRcvd(message)
        }
    }
}

View Model

class MainViewModel: ObservableObject {
    @ObservedObject var websocketViewModel = WebsocketViewModel()

    ...
}

Websocket view model

class WebsocketViewModel: ObservableObject {
    @Published var messageRcvd: JSON?

    ...

    // this function gets triggered on new websocket messsage
    private func webSocketListener() {
        ...
        DispatchQueue.main.async {
            messageRcvd = json
        }
    }
}
2
  • I assume JSON is a struct? Commented Apr 2, 2022 at 21:55
  • With only a couple of exceptions SwiftUI wrappers only with inside a SwiftUI view the @ObservedObject wrapper needs to happen in the SwiftUI View Commented Apr 3, 2022 at 1:14

1 Answer 1

1

You need to observe when the websocketViewModel instance changes in MainViewModel.

You can do this by triggering objectWillChange.send() when the instance changes:

class MainViewModel: ObservableObject {
    let websocketViewModel = WebsocketViewModel()
    private var cancellable: AnyCancellable?

    init() {
        cancellable = websocketViewModel.objectWillChange.sink { [unowned self] _ in
            objectWillChange.send()
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.