Search code examples
swiftreactive-programmingrx-swiftreactivekitswiftbond

Invalid update: invalid number of items in section 0 in Reactive Programming issue


I have big trouble because when I selected a cell in my collectionView and change my array Data I got this error message :

'Invalid update: invalid number of items in section 0. The number of items contained in an existing section after the update (2) must be equal to the number of items contained in that section before the update (2), plus or minus the number of items inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of items moved into or out of that section (0 moved in, 0 moved out).'

It happens before iOS 13. In iOS 13 and Upper works well. There is my code:

import UIKit
import ReactiveKit
import Bond

//Its in my viewModel

var arrayOfObjects = MutableObservableArray<MyObject>([])


  actionCollectionViewDidSelect.observeNext { [weak self] indexPath in
        guard indexPath.row != 0 else { return }
        guard let object = self?.arrayOfPhotoObjects[indexPath.row] else { return }
        photoObject.isSelected = !photoObject.isSelected
        if let value = self?.arrayOfObjects.value { self?.arrayOfPhotoObjects.value = value } // Gives error because there but I can't find solution.
    }.dispose(in: disposeBag)

//Its in my ViewController


collectionView.reactive.selectedItemIndexPath.observe(with: viewModel.actionCollectionViewDidSelect).dispose(in: disposeBag)

    viewModel.arrayOfObjects.bind(to: collectionView) { object, indexPath, collectionView in
        
        let objectForIndex = arrayObjects[indexPath.row]
       
            let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "photoBoxCollectionViewCell", for: indexPath) as! MYCEll
             cell.data = objectForIndex
            return cell
        }
    }

Solution

  • I found the problem it was while I try to change my array it goes to trouble. My solution is :

      actionCollectionViewDidSelect.observeNext { [weak self] indexPath in
        guard indexPath.row != 0 else { return }
        guard let object = self?.arrayOfPhotoObjects[indexPath.row] else { return }
        photoObject.isSelected = !photoObject.isSelected
        if let value = self?.arrayOfObjects.value {                     
                let collection = value.collection
                let newArrayObject = MutableObservableArray<PhotoObject(collection)
                self?.arrayOfPhotoObjects.value = newArrayObject.value }
       }.dispose(in: disposeBag)