0

The error is below,

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.

How can I add this function to the task and return the task.?

func fetchAdPosts() async {

    Task {
        do{
            let db = Firestore.firestore().collection("Ads")
            
            let ads = try await db.getDocuments()

            //error in the below code lines
            self.ads = ads.documents.compactMap({ ad in
                return try? ad.data(as: AdPost.self)
            })
            
        }
        catch{
            
            self.alertMessage = error.localizedDescription
            showAlert.toggle()
        }
    }
    
}
Sasitha Dilshan
  • 111
  • 2
  • 15

1 Answers1

1

Firstly, if the function is already async, you don't really need to wrap the entire body in a Task as well. You don't need to introduce a new async context when you are already in one.

To resolve the error, ensure that the function is in an ObservableObject class marked @MainActor.

@MainActor class MyController: ObservableObject {
    // properties...
    
    func fetchAdPosts() async {
        do {
            let db = Firestore.firestore().collection("Ads")
            
            let ads = try await db.getDocuments()
            
            self.ads = ads.documents.compactMap({ ad in
                return try? ad.data(as: AdPost.self)
            })
        } catch {
            self.alertMessage = error.localizedDescription
            showAlert.toggle()
        }
    }
}

This will ensure that the assignment to self.ads takes place on the main actor, which is required for ObservableObject instances. The main actor context will be inherited for all properties and methods on a class marked @MainActor.

Bradley Mackey
  • 6,777
  • 5
  • 31
  • 45