The demo code below presenting a view with a number incrementing per second.
The problem is:
Each time data updated in VM, the menu ( top line of MacOS) will also been refreshed, which will interrupt user's operation.
Here is the code:
*App.swift
struct MemoryTestApp: App {
@ObservedObject var appVM = VM()
var body: some Scene {
WindowGroup {
ContentView(vm: appVM)
.environmentObject(appVM)
}
.commands {
CommandMenu("Menu1") {
Button("Test Btn") {
print("Test Btn pressed!")
}
}
}
}
}
VM
class VM: ObservableObject {
@Published var count = 0
func startCount() async{
while 1 == 1 {
DispatchQueue.main.async {
self.count += 1
if self.count > 1000 {
self.count = 0
}
}
do{
try await Task.sleep(nanoseconds: 1_000_000_000)
}catch{}
}
}
}
View
struct ContentView: View {
@ObservedObject var vm: VM
var body: some View {
Text("Hello, world! \(vm.count)")
.frame(width: 100, height: 100)
.onAppear(perform: {
Task{await vm.startCount()}
})
}
}
MacOS Monterey Xcode: 13.2.1