I'm following this tutorial on using MVVM with Retrofit
https://medium.com/@ronkan26/viewmodel-using-retrofit-mvvm-architecture-f759a0291b49
where the user places MutableLiveData inside the Repository class:
public class MovieRepository {
private static final ApiInterface myInterface;
private final MutableLiveData<EntityMovieOutputs> listOfMovies = new MutableLiveData<>();
private static MovieRepository newsRepository;
public static MovieRepository getInstance(){
if (newsRepository == null){
newsRepository = new NewsRepository();
}
return movieRepository;
}
public MovieRepository(){
myInterface = RetrofitService.getInterface();
}
I'm building a simple app and what I noticed is my repository class is quickly being filled with a lot of MutableLiveData objects. Is this actually the correct way to implement MVVM, LiveData, and the Repository pattern?
Edit1:________________________________________________
I've created an AdminLiveData
object that just holds the LiveData and has getters.
But how would I get reference to the ViewModel
inside my AdminRepo
class so I can notify the LiveData
inside the ViewModel when the Retrofit Network call is complete?
private AdminService adminService;
public AdminRepo(Application application) {
BaseApplication baseApplication = (BaseApplication) application;
RetrofitClient client = baseApplication.getRetrofitClient();
adminService = client.getRetrofit().create(AdminService.class);
//AdminViewModel viewModel = (AdminViewModel) ....
// Not sure how to get reference to the viewmodel here so I can get the
// LiveData object and call postValue after the retrofit calls
}
public void getFirstPageMembers(int offset, int limit) {
adminService.getUsersPaginitation(offset, limit).enqueue(new Callback<List<UserInfo>>() {
@Override
public void onResponse(@NonNull Call<List<UserInfo>> call, @NonNull Response<List<UserInfo>> response) {
if (response.body() != null) {
//firstPageLiveData.postValue(response.body());
//Since I create the LiveData inside the ViewModel class
//instead, how do I get reference to the ViewModel's LiveData?
}
}
@Override
public void onFailure(@NonNull Call<List<UserInfo>> call, @NonNull Throwable t) {
//firstPageLiveData.postValue(null);
}
});
}
The AdminViewModel
:
public class AdminActivityViewModel extends AndroidViewModel {
private AdminRepo repo;
private AdminLiveData adminLiveData = new AdminLiveData();
public AdminActivityViewModel(@NonNull Application application) {
super(application);
repo = new AdminRepo(application);
}
How do I get reference to the AdminViewModel
from inside my AdminRepo
class?