SwiftUI:让后台线程等待 UI 更新

huangapple go评论47阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年5月28日 23:07:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76352136.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定