4

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 ?

  • do it in your model! if your View have to reflect some final state... expose the state via property of your model. SwiftUI is a presentation layer – user3441734 Feb 02 '20 at 18:30

2 Answers2

6

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
}
Asperi
  • 228,894
  • 20
  • 464
  • 690
  • Does it exist a kind of willReceive() that catches the published value just before the published variable will change ? – Giuseppe Roberto Rossi Feb 07 '20 at 23:46
  • A bit late, but for reference. Yes, you must use the newValue as it contains the updated change. Do not use the self.users.$listaUtenti in the block or in any function you call from the block as it does not yet contain the change. – Brett Feb 26 '21 at 05:11
0
class Utenti : ObservableObject {

    @Published var listaUtenti = ["anna", "smith", "david"]  {
         didSet {
             // your func here
         }
    }
}

In the above code, whenever listaUtenti element changes your function will execute.

pkamb
  • 33,281
  • 23
  • 160
  • 191
koreaMacGuy
  • 75
  • 2
  • 8