Original MVVM applied to iOS. Properties and Commands

I have been developed iOS applications within MVVM architecture for a long time and every time I start new project I try to reduce distance between “perfect” MVVM and my MVVM.

This time I try to get closer to what I saw when searched for original MVVM applications within WPF. I noticed that there are two main players: Properties of a ViewModel, that represent state of a View, and Commands, whose execution is triggered from within a View and processed in the context of the ViewModel.

In this article we will try to create something similar using my favourite iOS binding framework Bond.

First, let’s take a look at our simple view controller in its initial form (I have configured it in storyboard):

On this view user will type a name in the text field, tap “Say Hello” button after what greeting label will update its text.
It’s clear that the view’s ViewModel should have two properties (name, greeting) and one command (say hello).

Thus, the ViewModel in its initial form will be like this:

Now, let’s transform all of this to usual MVVM look. We will make properties Observable and bind label and text field to them. Also we will bind button tap to sayHello function call.

Check gists below

It seems to be okay and it actually is, but as I said there should be Command player. Here command is obviously sayHello, but it’s represented as a simple function that is called from View. It would be better to describe this function as ViewModel’s property, so we can bind button tap to it with one line of code.

Let’s declare simple Command protocol.

Command must be able to bind signal to itself and execute some logic in response to the signal.
Let’s create concrete implementation of this protocol. We will declare class that will be initializing with action closure and execute it in execute function.

Now let’s wrap our sayHello function into sayHelloCommand:

Now it’s time to bind button tap to this command. One graceful line instead of three… Check out line number 20:

That is all! Let’s build and run our app:

There are a lot more types of commands you can create, just dive into it.
Thanks for reading!

There is also Combine framework version of the project: check out combine-framework branch: https://github.com/IsaAliev/MVVM-Properties-and-Commands/tree/combine-framework

GutHub:

iOS-Developer from Russia