Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to publish change from async function

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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
    }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading