Search code examples
swiftswiftuicombine

SwiftUI @Published and main thread


Could someone explain why I get this warning: 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'm know that if I wrap the changes in DispatchQueue.main.async the problem goes away. Why does it happen with some view modals and not others? I thought that since the variable has @Published it's automatically a publisher on main thread?

class VM: ObservableObject {
    
    private let contactsRepo = ContactsCollection()
    
    @Published var mutuals: [String]?
    
    func fetch() {
        contactsRepo.findMutuals(uid: uid, otherUid: other_uid, limit: 4) { [weak self] mutuals in
            guard let self = self else { return }
            if mutuals != nil {
                self.mutualsWithHost = mutuals // warning...
            } else {
                self.mutualsWithHost = []
            }
        }
    }
}

Solution

  • Evidently, contactsRepo.findMutuals can call its completion handler on a background thread. You need to ward that off by getting back onto the main thread.