为什么在函数中使用时发布变量的更新值没有得到反映?

Why is the published variable's updated value not getting reflected when used in function?

我正在尝试按照此 tutorial 将 WatchConnectivity 与 SwiftUI 结合使用。在手表的视图模型中,我能够成功接收到从 iPhone 发送的消息并将其设置在 class 的已发布变量中,但是当我尝试在ContentView,我只看到了初始值,没有看到更新后的值。

ViewModelWatch

import Foundation
import WatchConnectivity

class ViewModelWatch : NSObject,  WCSessionDelegate, ObservableObject{
    var session: WCSession
    @Published var sessionId = ""
    
    init(session: WCSession = .default){
        self.session = session
        super.init()
        self.session.delegate = self
        session.activate()
    }
    
    func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) {
        
    }
    
    func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
            DispatchQueue.main.async {
                if let sessionId = message["sessionId"] {
                    self.sessionId = sessionId as! String
                }
            }
        }
}

ContentView

import SwiftUI

struct ContentView: View {
    @ObservedObject var model = ViewModelWatch()
    
    var body: some View {
        Button(action: startAction, label: {
          Text("Test")
        })
      
       
    }
    
    func startAction() {
        print("sessionId", self.model.sessionId)

    }
}

@Asperi - How would you recommend getting the updated sessionId value then?

一个解决方案是将动作移动到模型中,因此它使用自己的 属性 进行操作,并直接在按钮(或按钮动作闭包)中使用该动作,例如

class ViewModelWatch : NSObject,  WCSessionDelegate, ObservableObject{

    // ... other code

    func startAction() {                     // << move here
        print("sessionId", self.sessionId)

    }
}

struct ContentView: View {
    @ObservedObject var model = ViewModelWatch()

    var body: some View {
        Button(action: model.startAction, label: {     // << use model
          Text("Test")
        })
    }
}