I'm a beginner studying MVVM
design patterns.
Looking at the code of Google CodeLab
and other sample codes, a question arose.
As the title suggests, does LiveData
necessarily exist in the Repository
?
I've been using and observing LiveData
in a ViewModel
so far.
(There's no special reason, I just used it because I didn't know anything)
By the way, I looked at the code of Google CodeLab
to study Room
, and I saw that it uses LiveData
(or Flow
) in the Repository
and reference this in LiveData of the ViewModel
.
Sample code from other web sites was similar.
But I don't know why LiveData
is in the Repository
and uses the way it's referenced.
Since LiveData
is used in the Repository
in the code of official docs such as CodeLab
, I am using it accordingly, but I do not know why.
In the MVVM
pattern, does LiveData
necessarily exist in the Repository
? I'd appreciate it if you could explain why.
CodePudding user response:
LiveData is simply an observable data holder. It is lifecycle aware so it is a good practice to use it for providing data to View from ViewModel. LiveData can now be replaced with Flow which have few benefits over LiveData.
From Repository to ViewModel, it is completely up to you whether you want a LiveData/Flow returned or simply return the model that you expect from DAO but still you will require a LiveData/Flow if you want to provide that model to View after receiving that model from Repository to ViewModel.
CodePudding user response:
The MVVM pattern is more about designing software, and organising the architecture into separate layers. The View is the user-facing frontend, the Model is the backend where the data is handled.
The View Model sits between them, converting data from the Model into some form of UI state the View can display, and turning UI events like button presses into calls to the app's backend functions, in the Model.
LiveData
and Flow
(which are similar - one is Android and one is Kotlin) are ways of exposing data, which is ultimately what the Model does - producing data. Instead of just providing a single value on request, they're able to provide a stream of data.
And the View Model (which is the intermediary between the Model and View - they don't talk to each other) can take that LiveData
or Flow
, and either expose it directly to the View, or do some processing on it to produce data suitable for the View to display. That way you have a pipeline from the data producer (the Model) to the UI (the View). That's basically how MVVM works in general, this is just using the streaming/producer/reactive model to wire things up and make things like async operations simpler
This is worth a read, it explicitly mentions repositories as the data producer in this model: https://developer.android.com/kotlin/flow