Can you explain the differences between ViewModel,...
# android-architecture
c
Can you explain the differences between ViewModel, UseCase, Repository?
c
this is just my opinion: ViewModel typically in android is a AAC (android arch components) ViewModel. This lives beyond the lifecycle of your typical view in order to paper over configuration changes. UseCase is one way of modelling your interactions from view layer into domain layer. Represents a "use case" Reposotiry layer is like an api for your api.
j
• vm -> presentation logic to avoid having logic non UI logic on the UI. • use cases -> units of business logic, the minimum expression of any behavior related to the business • repository -> abstract and merge multiple data sources
e
I miss the days when ViewModel meant an object that … modelled the view. That ship has sailed however.
c
Thanks. Um, I can't draw the concept clearly in my head. 😞
j
Here's how I understand it - say you're building a shopping app, and the user wants to add a discount coupon. •
repository
talks to the data layer (api/local dbs etc) •
usecase
uses
repository
to get the required data (discount code validation, discount calculation, etc) and also manipulate final response if required. •
viewmodel
calls the
usecase
upon user action and also handles UI update at the end. this way, business logic would stay within
usecase
,
viewmodel
would only be responsible for user actions and ui updates,
repository
abstracts the data layer.
j
I believe use cases is what people struggle the most. There not necessarily needed in all cases. Where abstracting data layer from ui is easy to grasp. Often you have a bunch of methods (glue code) all over the place in your, e.g. ViewModel that kind of belong together but it doesn't quite make sense to create a whole new class for it. With use cases you can group them and give them a name.