In my Android application, im the following architecture components with the mvvm template. my app makes a network call to display weather information. A call is made from a repository that returns a live response group to the viewmodel, which is related to my main activity.
the application works fine, except for one condition, whenever I turn off the Internet to test the case of a crash, it inflates viewing errors as needed
in the error view, I have a redo button that makes the method call again observe the view model (this method was also called oncreate () for the first time that worked)
even after turning on the Internet and pressing the snooze button, which listens to the observed. If the data becomes empty.
I do not know why. Please, help
WAREHOUSE
@Singleton public class ContentRepository { @Inject AppUtils mAppUtils; private RESTService mApiService; @Inject public ContentRepository(RESTService mApiService) { this.mApiService = mApiService; } public MutableLiveData<ApiResponse<WeatherModel>> getWeatherListData() { final MutableLiveData<ApiResponse<WeatherModel>> weatherListData = new MutableLiveData<>(); mApiService.getWeatherList().enqueue(new Callback<WeatherModel>() { @Override public void onResponse(Call<WeatherModel> call, Response<WeatherModel> response) { weatherListData.setValue(new ApiResponse<>(response.body())); } @Override public void onFailure(Call<WeatherModel> call, Throwable t) { weatherListData.setValue(new ApiResponse<>(t)); } }); return weatherListData; } }
ViewModel
public class HomeViewModel extends AndroidViewModel { private final LiveData<ApiResponse<WeatherModel>> weatherListObservable; @Inject public HomeViewModel(Application application, ContentRepository contentRepository) { super(application); this.weatherListObservable = contentRepository.getWeatherListData(); } public LiveData<ApiResponse<WeatherModel>> getWeatherListObservable() { return weatherListObservable; } }
OBSERVING METHOD IN ACTIVITIES
private void observeViewModel() { mHomeViewModel = ViewModelProviders.of(this, mViewModelFactory).get(HomeViewModel.class); mHomeViewModel.getWeatherListObservable().observe(this, weatherModelApiResponse -> { if (weatherModelApiResponse.isSuccessful()) { mErrorView.setVisibility(View.GONE); mBinding.ivLoading.setVisibility(View.GONE); try { setDataToViews(weatherModelApiResponse.getData()); } catch (ParseException e) { e.printStackTrace(); } } else if (!weatherModelApiResponse.isSuccessful()) { mBinding.ivLoading.setVisibility(View.GONE); mDialogUtils.showToast(this, weatherModelApiResponse.getError().getMessage()); mErrorView.setVisibility(View.VISIBLE); } }); }
RETRY BUTTON IN ACTIVITY
@Override public void onClick(View v) { switch (v.getId()) { case R.id.btn_retry: mErrorView.setVisibility(View.GONE); observeViewModel(); break; } }