Search code examples
swiftuiconcurrency

SwiftUI: Have background thread wait for UI update


I have SwiftUI app with a background thread running a simulation. At certain points in the simulation I want to display the current state in the UI.

I can notify the system that the UI needs updating by changing an @Published property. However, I really need the simulation to then pause until the UI update is complete. That way it will display the current results as opposed to the state of the simulation sometime later when the UI gets around to updating.

I assume this must be possible, but I haven't found it in the somewhat complex concurrency model for SwiftUI.

Thanks


Solution

  • This is the entire intent of having a @Published property. This property must only be updated on the UI thread (the main queue, the main actor, etc). When the update is to happen, the engine should write to the @Published property, which will cause the UI to update on the same thread, blocking until it completes. As long as you update the UI entirely based on the @Published property, your system will remain consistent.