0

I want to delete the object from the snapshot using swipe to delete, but first I need to make a network call which is located in view model. If the result is success, then remove the object, otherwise do nothing.

I am using custom view model class for fetching data and appending sections and items and I would also prefer that view model handles all network calls. Putting network call in tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) is not an option.

This is an example:

import UIKit

struct MySectionType: Hashable {}

struct MyItemType: Hashable {}

class MyViewModel {
    func deleteItem(item: MyItemType) {
        // Network call...
    }
}

class MyViewController: UIViewController {
    var viewModel: MyViewModel

    // MARK: - Initialization
    init?(coder: NSCoder, viewModel: MyViewModel) {
        self.viewModel = viewModel
        super.init(coder: coder)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    class DataSource: UITableViewDiffableDataSource<MySectionType, MyItemType> {
        override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
            return true
        }
        
        override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
            if editingStyle == .delete {
                if let item = itemIdentifier(for: indexPath) {
                    // Call viewModel deleteItem
                    // viewModel.deleteItem(item: item)
                    
                    // If success - deleteItems
                    var snapshot = self.snapshot()
                    snapshot.deleteItems([item])
                    apply(snapshot)
                }
            }
        }
    }
}
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Marko Kos
  • 33
  • 8
  • *Putting network call in tableView… is not an option*. Why not? You have to call the network request when the swipe action is triggered. But use the contemporary swipe action API which is designed to work asynchronously. And `deleteItem` must be asynchronous, too. – vadian Dec 15 '21 at 13:28
  • you must not delete items from the snapshot. When using diffabledatasource, you must delete the item from your array, then `apply` a new snapshot. – Tad Dec 16 '21 at 01:33
  • I agree, but the problem is that my view model is not available in the DataSource class. – Marko Kos Dec 16 '21 at 08:02

0 Answers0