T
T
Tkas2018-12-09 15:00:53
iOS
Tkas, 2018-12-09 15:00:53

Data binding in the view model with the controller with RxSwift (MVVM pattern). Is my decision correct?

I want to achieve that my collectionView is updated after deleting data from Core Data. To do this, I have a FoodViewModel with the following content:

class FoodViewModel: FridgeCollectionVIewViewModelType {

    public var oldData = Variable<[FoodBySections]>([])
    public var foodBySections = Variable<[FoodBySections]>([])
    private var foods: [Food]?
  
   //какой-то код
   ....
   //код удаления
       func deleteFood(forIndexPath indexPath: IndexPath) {
        let objectToDeleteName = self.foodBySections.value[indexPath.section][indexPath.row].name!
        
        oldData.value = foodBySections.value
        CoreDataHelper.sharedInstance.deleteFoodFromFridge(foodName: objectToDeleteName)
        foods = CoreDataHelper.sharedInstance.fetchFoods()
        foodBySections.value = FoodBySections.split(foods: foods!)
    }
}

In the code above, the last foodBySections initialization will serve as newData to update the collectionView. The ViewController code snippet is as follows:
class FridgeCollectionViewController: UICollectionViewController, UIGestureRecognizerDelegate {

    @objc func deleteFood(gesture: UILongPressGestureRecognizer!) {
        if gesture.state != .ended {
            return
        }
        
        let point = gesture.location(in: self.collectionView)
        
        if let indexPath = self.collectionView?.indexPathForItem(at: point) {
            self.foodViewModel?.deleteFood(forIndexPath: indexPath)
            
            var newData: [FoodBySections]?
            _ = self.foodViewModel?.foodBySections.asObservable().subscribe {
                newData = $0.element!
            }

            var oldData: [FoodBySections]?
            _ = self.foodViewModel?.oldData.asObservable().subscribe {
                oldData = $0.element!
            }
            
            self.collectionView.animateItemAndSectionChanges(oldData: oldData!, newData: newData!)
        }
    }
}

That is, I get oldData from the view model and newData (the last initialization of foodBySections) also from the view model. And I send them to update the collection (collectionView.animateItemAndSectionChanges). Question: Is the given code correct? Or can this problem be solved much better (using reactivity)?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Igor Cherny, 2018-12-09
@freeg0r

To track the state of the CoreData table and update the UI, there is a ready-made convenient solution: NSFetchedResultsController , just delete the required entry from Core Data, and the table will update itself.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question