I have class conforms to ObservableObject with
@Published var fileContent = ""
defined. Further I have getFileContent() async function returning String. If I call function like this
Task {
fileContent = await getFileContent(forMeasurementID: id, inContext: context)
}
code is compiled and app works fine but XCode is complaining "purple" error "Publishing changes from background threads is not allowed; make sure to publish values from the main thread (via operators like receive(on:)) on model updates.". I've tried to elaborate with receive(on:) but no succeess so far. I will appreciate any hint. Thanks.
Well, in async/await world it is better to use MainActor, e.g.
Task {
let content = await getFileContent(forMeasurementID: id, inContext: context)
await MainActor.run {
// fileContent will be updated on the Main Thread
fileContent = content
}
}
You cannot change the state of your app (change a @Published
var) unless you are in the main thread.
Here is how your code works:
Task {
let content = await getFileContent(forMeasurementID: id, inContext: context)
DispatchQueue.main.async {
fileContent = content
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With