Hey everyone! Still trying to get the hang of MVVM...
# android-architecture
a
Hey everyone! Still trying to get the hang of MVVM here I’m having some issues with handling events from the view Let’s say I have a view where I can create a new flower. When I click “Add” i want my flower to be saved to my repository I’m currently calling a
saveFlower(flowerData:FlowerData)
method in my viewModel from my Fragment and passing it all the fields values. The ViewModel that holds my FlowerRepository is then creating the proper Flower object and saving to the FlowerRepository This feels wrong to have the ViewModel both presenting data and handling it, what should I do?
o
IMO - your VM should be holding state + business logic. Your view sets a listener, and calls a method on the VM to let the VM know some action has been taken. If no UI data is really needed, then your VM can just pass that action along to the repo and the repo can update your data layer/make API calls w/e it needs to do. If there's some data that needs to be passed along from the view then the view would pass those params to the VM method and then your VM passes that info along as well. The VM shouldn't know about anything in the data layer. That includes the data models, DB, network layer etc. So if it's a data model that gets created and inserted into your DB, then the repository would be the one responsible for creating that and updating.
a
Alright nice! It’s just that I feel like the ViewModels grow bigger and bigger and handle everything. Have you ever tried splitting the ViewModel between state and business logic?
o
That's exactly the issue sort of with putting everything in view models. It's hard because technically it makes sense to live there, but then it just blows up the ViewModel just like the old days when everything was in the activity or fragment. I personally havent needed to break up my ViewModel into another presenter or something similar, because I try to break out common business logic or state to multiple view models when I can. But if the case came around where I did have some Godly ViewModel, then definitely I think it makes sense to break it apart if you can. Ideally though, if you could have your ViewModel just hold some type of UI state object, and keep all the business logic there, then it shouldn't get too cluttered.
a
Thanks for the help Omid! I’ve set-up a ViewState in my ViewModel to make it easier to update from the ViewModel and observe from the View. I’ve also resorted to using UseCase classes in my ViewModel since a lot of the events throughout my app were doing similar things and I wanted to avoid duplication I think I’m pretty satisfied with my current implementation, the code is a LOT less cluttered !