X
X
xllnc2019-08-16 22:40:08
Android
xllnc, 2019-08-16 22:40:08

Why is LiveData value null?

MainActivity

mViewModel = ViewModelProviders.of(this).get(ListIssueViewModel.class);
        mViewModel.getApiResponse().observe(this, apiResponse -> {
            mAdapter.addIssues(apiResponse.getIssues());
        });
        mViewModel.loadIssues("square", "retrofit");

viewmodel
private MediatorLiveData<ApiResponse> mApiResponse = new MediatorLiveData<>();
public void loadIssues(String user, String repo){
        mApiResponse.addSource(
                mIssueRepository.getIssues(user, repo),
                new Observer<ApiResponse>() {
                    @Override
                    public void onChanged(ApiResponse apiResponse) {
                        mApiResponse.setValue(apiResponse);
                    }
        });
    }

Repository code:
@Override
    public LiveData<ApiResponse> getIssues(String owner, String repo) {
        final MutableLiveData<ApiResponse> liveData = new MutableLiveData<>();
        Call<List<Issue>> call = mApiService.getIssues(owner, repo);
        call.enqueue(new Callback<List<Issue>>() {
            @Override
            public void onResponse(Call<List<Issue>> call, Response<List<Issue>> response) {
                liveData.setValue(new ApiResponse(response.body()));
            }

            @Override
            public void onFailure(Call<List<Issue>> call, Throwable t) {
                liveData.setValue(new ApiResponse(t));
            }
        });
        return liveData;
    }

So, when I do it as above, everything works, but when I change the ViewModel code to:
private MutableLiveData<ApiResponse> mApiResponse = new MutableLiveData<>();

public void loadIssues(String user, String repo){
  LiveData<ApiResponse> livedata = mIssueRepository.getIssues(user, repo);
  mApiResponse.setValue(livedata.getValue());
}

That returns null, why, it's not the same thing ??
Changed MediatorLiveData to MutableLiveData and everything broke. It seems to me that I didn’t understand the intricacies of how LiveData works, and now I’m sitting and I can’t understand why null is returned, although there are no errors in the API request itself, because I didn’t touch it and it’s working.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question