英文:
SwiftUI: Have background thread wait for UI update
问题
我有一个使用SwiftUI的应用程序,其中有一个后台线程正在运行模拟。在模拟的某些点上,我想在UI中显示当前状态。
我可以通过更改一个@Published属性来通知系统需要更新UI。但是,我真的需要模拟在UI更新完成之前暂停。这样,它将显示当前的结果,而不是模拟的状态,后来当UI开始更新时。
我假设这一定是可能的,但我在SwiftUI相对复杂的并发模型中没有找到它。
谢谢
英文:
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
答案1
得分: 1
这就是拥有@Published
属性的完整目的。此属性必须仅在UI线程上(主队列、主演员等)进行更新。当更新要发生时,引擎应该写入@Published
属性,这将导致UI在同一线程上进行更新,直到完成为止。只要您完全基于@Published
属性更新UI,您的系统将保持一致。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论