Reputation: 5651
I'm running into an issue where in Combine where I have a boolean @Published property.
When I set it to true, the sink closure is run and I can look at the value being received. It's true. But when I compare it against the actual property that I am observing, they are different.
This bit of code can be simply run in a playground. I'm not sure how this works or why the values would be different
class TestModel {
@Published var isLoading = false
}
let model = TestModel()
model.$isLoading.sink { (isLoading) in
if isLoading != model.isLoading {
print("values NOT same")
}
}
model.isLoading = true
Upvotes: 10
Views: 5149
Reputation: 385500
@Published
publishes the new value before it actually modifies the stored value. This is documented:
When the property changes, publishing occurs in the property’s willSet block, meaning subscribers receive the new value before it’s actually set on the property.
If the @Published
property is part of an ObservableObject
, it also triggers the enclosing object's objectWillChange
publisher before the new value is actually set on the property.
(This answer used to include a disassembly of part of the @Published
wrapper, but that is no longer needed because Apple has now documented the behavior.)
Upvotes: 29