I having issues trying to understand combine and publishers. I have a PhotoPicker that selects one ore more images from the photo library. These images should be added to my core data model. This is handled in my model class.
However, I ends up in an infinit loop that I don't understand. The View keeps updating and the onReceive method keeps executing over and over again making the View render again. Below is a sample code (without core data) that behaves the same
Sample code:
Can someone explain what is happening?
However, I ends up in an infinit loop that I don't understand. The View keeps updating and the onReceive method keeps executing over and over again making the View render again. Below is a sample code (without core data) that behaves the same
Sample code:
Code Block struct MyImage: Hashable { var id: String var uiImage: UIImage } class Model: ObservableObject { @Published var images: [MyImage] = [] func add(uiImage: UIImage) { let id = UUID().uuidString let image = MyImage(id: id, uiImage: uiImage) self.images.append(image) } } struct ContentView: View { @StateObject var model = Model() @State var showPhotoPicker = false @State var pickerResult: [UIImage] = [] var body: some View { VStack { ForEach(model.images, id: \.self) { image in Text(image.id) // TODO: Add actual image } Button(action: { showPhotoPicker.toggle() }) { Text("ADD PHOTO") } .fullScreenCover(isPresented: $showPhotoPicker) { let config = PHPickerConfiguration(photoLibrary: PHPhotoLibrary.shared()) PhotoPicker(configuration: config, pickerResult: $pickerResult) } } .onReceive(pickerResult.publisher, perform: { image in model.add(uiImage: image) }) } }
Can someone explain what is happening?