We can, but what's that trigger in practice? Is it the same as
if oldValue != value {
oldValue = value
...
or what?
Obviously we don't like to write triggers manually as it was the constant source of errors with trigger and observation getting out of sync because we'd changed one and forgot to change another.
Frankly this starts resembling what we had in UIKit:
I have no horse in that race. I'm just trying to add my own contribution to Dave's comment:
The moment you can name a variable without having it be an argument of your function (or a copied capture), you get reference semantics. Whether or not it's a bad thing is a different question.
If the heart of the problem is to find better ways to write and maintain observation triggers, then I'm sure there's a way to do it in a MVS world and that may be a very interesting research question. Otherwise, I may be tempted to conclude that observation is incompatible with a value-oriented model.
I suspect your example might be misleading. Let's assume this scenario: there are a textfield and a label in the UI. The label displays the text user input in the textfield in upper case.
struct Model {
var inputText: String {
didSet {
displayedText = inputText.uppeercased()
}
}
var displayedText: String
}
So you need to implement how a change propagate in your data model even in SwiftUI. What SwiftUI automates is to propage data model change to view.
I think Dave's comment is about how to implement the change in data model: using observer or a value based algorithm (I understand the latter as data processing flow). While in this simple example, observer works fine and an algorithm would be overkilling, but from my experience the observer approach doesn't scale.
But why does observer approach works for SwiftUI? I think it's just used to track changes, not to process changes. My guess is SwiftUI processes changes in a functional way too.
I think it should be considered to move the onChange call to after cleaning up subscriptions in the withObservationTracking function.
let values = list.entries.mapValues { $0.addObserver {
onChange() // move from here
let values = state.withCriticalRegion { $0 }
for (id, token) in values {
list.entries[id]?.removeObserver(token)
}
// to here
}}
It currently works without issues due to the fact that ObservationRegistrar.State.willSet cancels a subscription for a given keyPath. However, moving the onChange call will make this code more robust.
EDIT: There are two point in which the subscription is cancelled: in withObservationTracking and in ObservationRegistrar.State.willSet. One of them is redundant, e.g. if you move onChange you could remove cancel call in willSet.
@Philippe_Hausler Are you and the team aware of any performance issues in the current implementation?
After using things for a few weeks and migrating some model code from Combine and ObservableObject to @Observable I decided to benchmark both approaches and was surprised to see the @Observable version was about 10x slower, and spent 10% of its time in access(_ keyPath:) via _swift_getKeyPath(pattern:arguments:).
I know @Joe_Groff has mentioned in the past that there are still performance wins to be made with key paths:
I'm curious if this performance is to be expected long term, if improvements are in the pipeline, or if it'd be helpful to dive deeper into the problem.
The issue with key paths is a known sore spot. This is definitely something that should be explored more not per se with how observation uses it but as you found out - the intrinsics for building key paths has a performance implication.
Quite honestly key paths are the right tool for the job here - they just need to be more refined. However it is a small hot spot in comparison to the savings of avoiding excessive rendering. The savings from avoiding unwanted rendering vastly out weighs the impact of key paths being formed (unless you are in a severe degenerate case).
Any wins needed to remedy the impact would likely pose some distinct wins in many other areas too - so from an engineering focus standpoint I would think it would be something that we should consider devoting resources to. If someone is interested in delving into that part of it I would be happy to share my findings as well as some ideas on how we could turn the costs into a practically insignificant impact. (but perhaps on another thread than the review of observation).
Can you clarify how forming keypaths avoids âexcessive renderingâ, and what this means for an app that doesnât use observation for ârenderingâ (which I presume refers to SwiftUI-style invalidation)? Will non-SwiftUI use cases suffer a net perf regression by switching to @Observable?
The execution of the closure is needed to be guaranteed across the start to end; meaning that the values must be changed sequentially and non-asynchronously. Furthermore thread locals are accessible from non-async contexts: e.g. when the property getter (which cannot be forced to be async) is accessed.
That means that to accomplish the tracking we need a scope local (aka thread local) for tracking, and cannot force non-async getters to reach out to a task local. Plus there is an extra cost for rendering side that was quite delicate; thread locals in that case compile down to a single machine instruction on some architectures.
Within the scope of the initial task, the changes will occur sequentially. With the scope of a nested task, the parent value will be shadowed, not overridden. So, I don't see where an inconsistency may occur. Am I wrong?
I agree on this. But I also have a pitch in mind to allow for more efficient usage of task local storages. Specifically, one downside of the current task local system is the requirement to use heap-allocated objects as keys. In many cases this could be avoided.
Well, I'm not entirely sure I can help you there, because I have an issue with the word âmagically.â When stuff happens magically that usually means local reasoning has been lost⌠so I'm opposed to magic in programming. The whole point of value semantics is to retain local reasoning.
If you're willing to settle for non-magic, you could take the approach SwiftUI, Photoshop, the desktop software I developed way back in prehistoryâand I'm sure countless other systemsâtake to this problem:
Make your data structure a value
Use CoW so similar values of the data structure created by small mutations share lots of storage
Make it efficient to compare parts of the data structure for equality and describe the differences between one value and another (didn't Foundation add collection diffing facilities some years ago?)
Take a snapshot of your data structure before making a series of changes
Compare the snapshot with the new state to see what changed and do whatever you need to do in response to those changes.
(This is super convenient if you need to be able to undo changes, because your undo history can just be a series of snapshots)
This is just one way to do it. I'm sure you can think of others.
Notice that steps 3 and 5 involve first-class algorithms that allow you to describe the behaviors of the system coherently rather than as a scattered set of observation actions.
And this is exactly the key. More generally, reference semantics doesn't scale because it undermines local reasoning.
I think the discussion of âwhy not use observation?â has been very interesting, but this review is certainly not going to result in the removal of reference semantics from Swift. And I highly doubt that even if the language workgroup decides to reject this proposal that SwiftUI, Combine, and Foundation will deprecate all existing forms of observation. So it might be a good idea to split out these posts into a new thread and limit the discussion here to the question of how well this specific revision of the proposal satisfies the assumed goal of adding observation to the standard library.
Good idea to move the thread, but, lest my intentions be misinterpreted: the discussion has been about "whether observation fits with value semantics and how to handle the same kinds of problems with pure value semantics,â and nobody's suggesting removing reference semantics from swift. I hadn't planned to say anything in this review and I've just been answering the questions people ask me. Not saying you explicitly said otherwise, but that seems like the implication.
I'm finding that property wrappers don't compose with the Observable macro. For example:
@propertyWrapper struct Wrapper<Value> {
var wrappedValue: Value
}
@Observable class Model {
@Wrapper var foo = "bar"
}
This results in two compiler errors, "Property wrapper cannot be applied to a computed property" and "Invalid redeclaration of synthesized property '_foo'". Wondering if this is a known issue and if it's a bug or an expected limitation of the macro.