MarkMe
MarkMe

Reputation: 51

Best way to communicate between ViewModel and Controller

I am new in development and recently practicing MVVM design pattern. To communicate between the ViewModel & Controller I am using Closure. I know I can use Delegate as well. But is there any convention or reason what particular way I should follow for the communication. I am confused a little bit. Any help will be appreciated.

Upvotes: 5

Views: 2371

Answers (2)

Soumen
Soumen

Reputation: 2110

I was also searching for this answer and I have found this,

Passing a closure from the UI Layer (UIL) to the Business Logic Layer (BLL) would break Separation of Concerns (SOC). The Data you are preparing resides in BLL so essentially you would be saying "hey BLL execute this UIL logic for me". That's an SOC. (Find more here https://en.wikipedia.org/wiki/Separation_of_concerns.)

BLL should only communicate with the UIL via delegate notifications. That way BLL is essentially saying, "Hey UIL, I'm finished executing my logic and here are some data arguments that you can use to manipulate the UI controls as you need to".

So UIL should never ask BLL to execute UI control logic for him. Should only ask BLL to notify him.

Here is the Link, you will get a clearer view.

Usage of MVVM in iOS

Upvotes: 7

user6338195
user6338195

Reputation:

You have lot options, depending on the structure of your app. One is using a singleton. I'm preferring this method for not too complex apps. The data handling (storing, structuring) located in the singleton class. The different views accessing the data from this singleton class. For example, you have a singleton named DataManager or something like that. The different controllers and other simple structures accessing the required data from this singleton.

Here is a very simple playground code for example:

class DataManager
{
    static let sharedInstance = DataManager()

    var _value: Int = 0
    var value: Int
    {
        get
        {
            return _value
        }
        set
        {
            _value = newValue
        }
    }
}

class DemoController1
{
    let dm = DataManager.sharedInstance

    func incValue()
    {
        dm.value += 1
    }
}

class DemoController2
{
    let dm = DataManager.sharedInstance

    func mulValue()
    {
        dm.value *= 2
    }
}

let dm = DataManager.sharedInstance
let dc1 = DemoController1()
let dc2 = DemoController2()

print ("value: \(dm.value)")
dc1.incValue()
print ("value: \(dm.value)")
dc1.incValue()
print ("value: \(dm.value)")
dc2.mulValue()
print ("value: \(dm.value)")

Upvotes: 0

Related Questions