'Correct way to implement ViewModel and LiveData with Repository in android using java?
I have red a lot of articles about correct implementing ViewModel and LiveData with Repository but every single one is different. Most of them are creating MutableLiveData inside the Repository even though the google document says:
It may be tempting to work LiveData objects in your data layer class, but LiveData is not designed to handle asynchronous streams of data.
And when it says data layer it means about the repository.
I am going to show some code that i wrote and how i have implemented this pattern. I have used the next principle:
public class MovieViewModel extends ViewModel {
private LiveData<List<MovieModel>> mMovies;
private MutableLiveData<MovieModel> mMovieDetails;
private MovieDao movieDao;
Repository mRepo;
private MovieViewModel() {
this.movieDao = App.getAppdb().movieDao();
this.mRepo = Repository.getInstance();
mMovies = movieDao.getMovies();
}
public LiveData<MovieModel> getmMovieDetails(String movieId) {
if (mMovieDetails == null) {
mMovieDetails = mRepo.getMovieDetails(movieId);
}
return mMovieDetails;
}
And the repository:
public class Repository {
public MutableLiveData<MovieModel> getMovieDetails(String id) {
MutableLiveData<MovieModel> tempMovieDetails = new MutableLiveData<>();
requests.getTvShowDetails(id).enqueue(new Callback<MovieModel>() {
@Override
public void onResponse(Call<MovieModel> call, Response<MovieModel> response) {
if (response.isSuccessful()) {
MovieModel movieDetails = response.body();
tempMovieDetails.postValue(movieDetails);
}
}
@Override
public void onFailure(Call<MovieModel> call, Throwable t) {
Log.d("ERROR:", t.getCause().toString());
}
});
return tempMovieDetails;
}
}
I have removed some boilerplate code as it is not in the scope of the question.
So my exact question is, is this the right way to implement ViewModel and LiveData with Repository(in this example i get data from API using Retrofit) even though i make MutableLiveData inside Repository and that clearly goes against the google docs. And if it's bad than can you provide me with a clean pattern.
Thanks!
Solution 1:[1]
MVVM architecture is a Model-View-ViewModel architecture that removes the tight coupling between each component. Most importantly, in this architecture, the children don't have a direct reference to the parent, they only have the reference by observables.
So I would suggest you to return the call in your activity instead of returning MutableLiveData and in case of using local database you can just return the live data from viewModel and observe that live data in activity.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Siddarth Jain |
