I have a problem with the following code, I am not being notified of changes to the progress property of my Job object, which is @Observable... This is a command-line Mac application (the same code works fine in a SwiftUI application).
I must have missed something?
do {
let job = AsyncJob()
withObservationTracking {
let progress = job.progress
} onChange: {
print("Current progress: \(job.progress)")
}
let _ = try await job.run()
print("Done...")
} catch {
print(error)
}
I Try this without any success:
@main
struct MyApp {
static func main() async throws {
// my code here
}
}
This is working for me.
The snippet you posted is missing the bits necessary to run it, so I filled those in as best I could. Pasted in at the end you’ll find the resulting code. I built this with Xcode 16.0 and ran it on macOS 14.7. Here’s what I see:
apply, 0
will do some work
change
did do some work
will do some work
did do some work
will do some work
did do some work
As you can see, the change handler fired when the run()
method updated progress
.
It only fired once, but such is the nature of withObservationTracking(_:onChange:)
: You have to re-observe each time.
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
import Foundation
import Observation
@Observable
class AsyncJob {
var progress: Int = 0
func run() async throws {
for _ in 0..<3 {
print("will do some work")
try await Task.sleep(for: .seconds(1))
self.progress += 1
print("did do some work")
}
}
}
func main() async {
do {
let job = AsyncJob()
withObservationTracking {
print("apply, \(job.progress)")
} onChange: {
print("change")
}
try await job.run()
} catch {
print(error)
}
}
await main()