I've just started tinkering with @Observable and have run into a question... What is the best practice for observing an Observable object outside of SwiftUI? For example:
@Observable
class CountingService {
public var count: Int = 0
}
@Observable
class ObservableViewModel {
public var service: CountingService
init(service: CountingService) {
self.service = service
// how to bind to value changes on service?
}
// suggestion I've seen that doesn't smell right
func checkCount() {
_ = withObservationTracking {
service.count
} onChange: {
DispatchQueue.main.async {
print("count: \(service.count)")
checkCount()
}
}
}
}
Historically using ObservableObject I'd have used Combine to monitor changes to service. That doesn't seem possible with @Observable and I don't know that I've come across an accepted / elegant solution? Perhaps there isn't one? There's no particular reason that CountingService has to be @Observable -- it's just nice and clean.
Any suggestions would be appreciated!