Search code examples
swiftevent-handlingselectorviewmodel

How do I handle callbacks when using selectors?


I'm placing my logic code in a viewModel. The view calls one method in the viewController. That method then calls the rest of the methods in the viewModel by using #selectors. This works fine up until the tableView needs to be reloaded with tableView.reloadData(). That part obviously needs to be in the view.

Normally, this would be accomplished by using multiple closures. But as #selectors can't have parameters I can't have a completion() callback in the last method that is called. So, my question is, how do I get around this problem? Is there any good alternatives to using #selectors? Should I have an observer in the view subscribing to the last method of the viewModel? Is RxSwift an alternative? Or is there a workaround using #selectors?


Solution

  • RxSwift is a good alternative, but in case you need something not as heavy, the delegate pattern is what you need:

    protocol ViewDelegate {
        // Other functions you might need
        func reloadTableView()
    }
    
    Then in your viewController, you implement these:
    
    class ViewController: ViewDelegate {
        func reloadTableView() {
            tableView.reloadData()
        }
    }
    

    And somewhere, in your view model you need to define the delegate:

    weak var viewDelegate: ViewDelegate
    

    As well as assign it when creating the classes:

    let model = ViewModel()
    let view = ViewController()
    
    model.viewDelegate = view
    

    Swift official documentation has a lot more on protocols: https://docs.swift.org/swift-book/LanguageGuide/Protocols.html