Skip to content

mvvm-delegates is not MVVM, actually that is MVP. #4

@marty-suzuki

Description

@marty-suzuki

Hi, @tailec

ViewModel has a reference of abstracted ViewController as Delegate in mvvm-delegation.
It means that is not MVVM, actually that is MVP.
@amadeu01 mentioned in #2 (comment) , too.

I have a doubt about #2 (comment) .

I think in MVP, presenter can have access to view (imports UIKit) but view models in MVVM are forbidden to do that.

I think differences between MVP and MVVM are those have references of View directly or not.

Presenter in MVP

Presenter has a reference of View (or ViewController) that is abstracted as protocol in almost cases.
To reflect state of Presenter, it calls method of abstructed View.

protocol CounterView {
    func didChangeCount(_ presenter: CounterPresenter, count: Int)
}

class CounterViewController: UIViewController, CounterView {
    let presenter: CounterPresenter
    let countLabel: UILabel

    override func viewDidLoad() {
        super.viewDidLoad()

        presenter.view = self
    }

    func countUp() {
        presenter.countUp()
    }
}

extension CounterViewController: CounterView {
    func didChangeCount(_ presenter: CounterPresenter, count: Int) {
        countLabel?.text = "\(count)"
    }
}

class CounterPresenter {
    private(set) var count: Int = 0 {
        didSet {
             view?.didChangeCount(self, count: count)
        }
    }

    weak var view: CounterView?

    func countUp() {
        count += 1
    }
}

ViewModel in MVVM

ViewModel must not depend on View (or ViewController).
Even if View is abstracted as Protocol, ViewModel must not depend on them.
To reflect state of ViewModel, it notifies changes of state with closure (or RxSwift.Observable and so on).
Closure is implemented outside of ViewModel, therefore ViewModel does not depend on View directly.

class CounterViewController: UIViewController {
    let viewModel: CounterViewModel
    let countLabel: UILabel

    override func viewDidLoad() {
        super.viewDidLoad()

        viewModel.countChanged = { [weak countLabel] count in
            countLabel?.text = "\(count)"
        }
    }

    func countUp() {
        viewModel.countUp()
    }
}

class CounterViewModel {
    private(set) var count: Int = 0 {
        didSet {
             countChanged?(count)
        }
    }

    var countChanged: ((Int) -> Void)?

    func countUp() {
        count += 1
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    invalidThis doesn't seem right

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions