swiftuiobservedobject

How to trigger an action as soon as a SwiftUI observed variable changes its value


I've got a List in my View where its elements are going to be updated as soon as the list argument will change. This is my View:

struct ContentView: View {
@ObservedObject var users = Utenti()
@State private var isSharePresented: Bool = false

var body: some View {
    VStack(spacing: 20) {
        HStack(alignment: .center) {
            Spacer()
            Text("Internal Testers")
                .font(.title)
                .foregroundColor(.primary)
            Spacer()
            Button(action: {
                self.isSharePresented.toggle()
            }) {
                Image(systemName: "square.and.arrow.up").font(.title).padding(.trailing)
            }.sheet(isPresented: self.$isSharePresented, onDismiss: {
                print("Dismissed")
            }, content: {
                ActivityViewController(activityItems: self.users.listaUtenti)
            })
        }
        List(self.users.listaUtenti, id: \.self) { user in
            Text(user)
        }
    }
}

}

List of users in the View

The variable users is an @ObservedObject, so the list content is updated automatically as soon as it changes in the Model.

My questions are: how can I catch the 'update' event concerning the users variable ? And how can I trigger an action (e.g. call a function) after catching it ?


Solution

  • Assuming that listaUtenti is @Published property you can catch its publisher as below

    List(self.users.listaUtenti, id: \.self) { user in
        Text(user)
    }
    .onReceive(self.users.$listaUtenti) { newValue in
         // do this what's needed
    }