If I assign the same value twice or more in succession to a @Published
member of an ObservableObject
, do both/all writes cause observers/receivers to receive updates with the same value, or does Combine suppress updates for assignments that don't actually change the value?
The answer is no. An @Published
property sends a change message every time you set a value on the property:
import Combine
class ModelObject: ObservableObject {
@Published var publishedProperty: Int = 0
}
let observeMe = ModelObject()
let subscription = observeMe
.$publishedProperty
.scan(0) { counter, _ in
counter + 1
}
.sink {
print("The number of changes is \($0)")
}
observeMe.publishedProperty = 1
observeMe.publishedProperty = 2
observeMe.publishedProperty = 2
observeMe.publishedProperty = 3
Prints:
The number of changes is 1
The number of changes is 2
The number of changes is 3
The number of changes is 4
The number of changes is 5
The first change is the original value of the property (0) then each of the four following changes causes the publisher to send an event even when the property is set to the value 2
more than once.