Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Analytics in MVVM

I use the MVVM in my project moreover I have analytics service outside the entire MVVM, but I don't know where call to analytics service, in ViewModels or in ViewCotrollers?

Example:

VIEW MODEL

login.request{ result in 
    //Here??
    Firebase.registerUser()
    viewController.finishLoginDelegate()
}

VIEW CONTROLLER

func finishedLoginDelegate() {
    //Or Here??
    Firebase.registerUser()
}
like image 339
Alvaro Avatar asked Nov 22 '17 11:11

Alvaro


Video Answer


1 Answers

This is a rather very interesting question. I have not read any blogs/documents dealing with the Analytics wrt MVVM.

In Analytics, there can be some cases where events are needed to be send for different stages of view lifecycle, whereas there would be some cases where only data matters. Couple this with the fact that most of the analytics are needed by Project Managers and they normally don't include them in specs, it becomes rather difficult to factor them when thinking about an app's or feature's architecture.

I have been guilty of putting a lot of analytics code in ViewControllers even when following MVVM. But, now when I think of it, I guess it is prudent to include an analytics layer(like ViewModel), for purely analytics related code. We can call it AnalyticsModel(for lack of better name).

We can write protocols related to it, pass on data and events from ViewController/ViewModel to this object and it can call Analytics API (is it me or there are just too many nowadays) and everybody can go back to assuming that they are happy in their own little world.

I have written the below code, to show how you can try writing AnalyticsModel.

protocol LoginAnalyticsModelProtocol {
    func loginViewAppeared()
    func loginButtonPressed(user:User)
    func signUpButtonPressed()
}


class LoginAnalyticsModel:LoginAnalyticsModelProtocol {
    func loginViewAppeared() {
        //call analytics to send login view appeared case
    }
    func loginButtonPressed(user:User) {
        // call analytics to send login view
    }
    func signUpButtonPressed() {
        // call analytics to submit sign up button pressed event
    }
}

class LoginVC:UIViewController {
    var loginVM:LoginViewModel?
    let loginAM:LoginAnalyticsModel = LoginAnalyticsModel()

    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        loginAM.loginViewAppeared()
    }

    @IBAction func loginButtonPressed(sender:UIButton) {
        // Get user
        // call anaytics
        loginAM.loginButtonPressed(user)
    }
}
like image 171
Puneet Sharma Avatar answered Sep 19 '22 19:09

Puneet Sharma