如何从异步函数发布更改

Daw*_*awy 2 async-await swiftui

我有符合 ObservableObject 的类

@Published var fileContent = ""
Run Code Online (Sandbox Code Playgroud)

定义的。此外,我有 getFileContent() 异步函数返回字符串。如果我这样调用函数

Task {
    fileContent = await getFileContent(forMeasurementID: id, inContext: context)
}
Run Code Online (Sandbox Code Playgroud)

代码已编译并且应用程序工作正常,但 XCode 抱怨“紫色”错误“不允许从后台线程发布更改;确保在模型更新时从主线程发布值(通过像 receive(on:) 这样的运算符)。”。我尝试详细说明 receive(on:) 但到目前为止没有成功。我将不胜感激任何提示。谢谢。

Mar*_*tis 11

好吧,在 async/await 世​​界中,最好使用 MainActor,例如

Task {
    let content = await getFileContent(forMeasurementID: id, inContext: context)
    await MainActor.run {
        // fileContent will be updated on the Main Thread
        fileContent = content
    }
}
Run Code Online (Sandbox Code Playgroud)