How to receive @Published var in main thread

Viewed 441

I keep the Model as a Published var in the ViewModel and Observe it from the View.

When the model process goes into a background thread, if you publish the model value, the Xcode thread checker will react.

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.

Is issued.

@StateObject var viewModel = ViewModel()
class ViewModel: ObservableObject {

    @Published var model = Model()
    var thisValue:String {
        return model.thisValue // I want to use this value in view
    }
struct Model {
    var thisValue:String = "value" // I want to change this value on background threads.

I'd like to know how to receive the model value in the main thread, but I didn't quite understand and asked a question.

I would be very happy if you could tell me.

1 Answers

Don't quite get what you are trying to do. But if you are not happy with DispatchQueue.main.async you may try one of the following options:

Combine

struct Model {
    var thisValue: String = "value"
}

class ViewModel: ObservableObject {
    @Published var model = Model()
    var thisValue: String {
        model.thisValue
    }
    func setThisValueInBackground() {
        DispatchQueue.global(qos: .background).async {
            Just(Model(thisValue: "newValue")).receive(on: RunLoop.main).assign(to: &self.$model)
        }
    }
}

Unpublish your model and use property observer on it instead

class ViewModelV2: ObservableObject {
    var model = Model() {
        didSet {
            thisValue = model.thisValue
        }
    }
    @Published private(set) var thisValue: String = ""
    func setThisValueInBackground() {
        DispatchQueue.global(qos: .background).async {
            self.model = Model(thisValue: "newValue")
        }
    }
}
Related