-
-
Save tonyarnold/120b4b3e1bd74cdd60080b5457842447 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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