swiftPunk
swiftPunk

Reputation: 1

How we can use ObservableObject in onChange/onReceive?

I have this code, which has a struct and ObservableObject. I am feeding my ObservableObject with some Buttons. I am trying get run some print in any changes of my ObservableObject, it should be working, but i do not know what I am missing.

PS: Also I want to know should I use .onChange or .onReceive for this work?

    struct Data: Identifiable
{
    let id  = UUID()
    var name: String
}

let dataTrain1 = [Data(name: "A"), Data(name: "A"), Data(name: "A"), Data(name: "A"), Data(name: "A")]
let dataTrain2 = [Data(name: "A"), Data(name: "B"), Data(name: "B"), Data(name: "A"), Data(name: "A")]


class DataModel: ObservableObject
{
    @Published var items: [Data] = []
}




struct ContentView: View
{
    
    
    @StateObject var dataModel = DataModel()
    
    var body: some View
    {
        
        
        
        ZStack
        {
            
            VStack
            {
                HStack
                {
                    
                    Button("Load dataTrain1") { dataModel.items = dataTrain1 }
                    
                    Spacer()
                    
                    Button("Load dataTrain2") { dataModel.items = dataTrain2 }
                    
                }
                .padding(.horizontal)
                
                Spacer()
            }
            
            HStack
            {
                ForEach(dataModel.items) { item in
                    
                    Text(item.name)
                        .font(.title)
                        .bold()
                        .foregroundColor(item.name == "A" ? Color.red : Color.blue)
                    
                }
 
            }
  
        }
        .onChange(of: dataModel.items) { _ in print("dataModel Changed!") } // ← Here
        .onReceive(dataModel.$items) { _ in print("dataModel Changed!") } // ← Here
        
        
    }
    
}

Upvotes: 1

Views: 967

Answers (1)

pawello2222
pawello2222

Reputation: 54601

To use onChange your Data must conform to Equatable.

struct Data: Identifiable, Equatable { ... }

Upvotes: 2

Related Questions