Team good morning i have one doubt anyone suggest ...
# android
r
Team good morning i have one doubt anyone suggest me the good way to solve below my problem I have one api call logic to use multiple activities and fragments. So do I need to define that method in one viewmode and that viewmodel needs to use all the places? But based on google documentĀ one activity should have only one view model. So how to do it now? Should I write logic for all the viewmodel?
stackoverflow 1
s
I think you can use inheritance here. Define your API call in ViewModelA and extend rest of the ViewModels with it
r
cool. thanks for your suggestion. i thought same but want get some suggestion. šŸ‘
d
Would it be better to use composition instead of inheritance here? For example, you can have some class where youā€™ll define your API call, and then you can create a repository class as an abstraction layer. Then, you can simply have a reference to that repository in the view models.
r
in that case my view model code is repeating in multiple view model class yes? for example VM1 calling Repository logic like getMyList and same VM2 also have etc.,
d
so the only code that would be repeating is
myRepository.networkCall()
, or is there any additional logic?
r
additional logic like showing loading indicator and exception handling etc.,
d
yeah, in that case it makes sense to have a base view model, but I would still create a repository and extract the API call logic into separate class, and then have the repository in that base view model.. this way you wonā€™t mix up presentation and data logic
šŸ‘ 1
i
an interactor or repository would be the right architectural pattern to use. just have an interactor that embed that logic and inject in every VM needed. Alternatively you can use a VM for that logic and make it open to be extended by all the rest of the VM.