Skip to content

Instantly share code, notes, and snippets.

@tonyarnold
Created December 1, 2023 04:59
Show Gist options
  • Save tonyarnold/120b4b3e1bd74cdd60080b5457842447 to your computer and use it in GitHub Desktop.
Save tonyarnold/120b4b3e1bd74cdd60080b5457842447 to your computer and use it in GitHub Desktop.
import Observation
import OSLog
import SwiftUI
@Observable
class CounterModel {
init(count: Int = 0) {
self.count = count
self.observe() // If I comment out this method, changes due to observation within the view work again.
}
var count = 0
func decrementButtonTapped() {
self.count -= 1
}
func incrementButtonTapped() {
self.count += 1
}
@Sendable func observe() {
withObservationTracking {
self.count
} onChange: {
self.logger.info("Count changed")
Task { @MainActor in
self.observe()
}
}
}
private let logger = Logger()
}
struct CounterView: View {
@Bindable var model: CounterModel
var body: some View {
let _ = Self._printChanges()
Form {
Section {
Text(self.model.count.description)
Button("Decrement") { self.model.decrementButtonTapped() }
Button("Increment") { self.model.incrementButtonTapped() }
} header: {
Text("Counter")
}
}
}
}
#Preview {
CounterView(model: CounterModel())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment