When the @Published publishes the value it wraps?

175 Views Asked by At

I've got the publisher

@Published var feedData = Feed()

And this piece of code, which listens to it

// some View 
.onReceive(feed.$feedData) { feedData in
            if feedData.personalTasks.count > 0 {
                withAnimation(.easeOut(duration: 0.3)) {
                    showCards = true
                }
            }
        }

The question is when .onRecieve will be executed? Every time feedData is accessed? Or every time any property of feedData is changed? How does this property wrapper know when something changes in feedData?

1

There are 1 best solutions below

0
On BEST ANSWER

.onReceive will be executed every time feedData is changed, which is when the Published publisher will emit a value.

If Feed is a value-type, like a struct, then anytime any of its properties change, the value-type semantics of Swift ensure that the entire object is being changed.

If Feed is a reference-type - a class, then only when setting feedData to a different instance would emit a value.