I 'm working on an Android App that I take entries from user and add them to Firebase to retrieve in the future but I confused about that do I need a viewModel for this operation. So, I know we need viewModels for business logic e.g grabbing data from an API or database but I have no idea about that Is it necessary when adding data to Firebase. If it does, I can't access the views where users enter data from a viewModel.
Can you explain do I need viewModel and if I do, how to access these views from viewModel ?
CodePudding user response:
I know we need view models for business logic.
Yes, that is correct. It's recommended to put your business logic in the ViewModel, as it should serve as the connector between our UI and the rest of your app. Besides that, bear in mind that the ViewModel it's a class that is designed to store and manage UI-related data that are lifecycle aware. It allows the data to survive configuration changes such as screen rotations.
but I have no idea about that Is it necessary when adding data to Firebase.
Yes, the read and the write operation should be managed through the ViewModel.
If it does, I can't access the views where users enter data from a ViewModel.
The views should never exist in the ViewModel class. You should only have objects that can be observed from the activity or fragment.
how to access these views from ViewModel?
It's exactly the opposite. You access (observe) the data in the ViewModel class from the activity or fragment classes. I have also written two articles that can help you understand the concept: