Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AndroidViewModel - Making duplicate calls doesn't return data in observe function

My question is related to ViewModel second time returns null wherein I am not getting callback inobserve function if I make a repeated call to server. Following is the code I am using -

@Singleton
public class NetworkInformationViewModel extends AndroidViewModel {
  private LiveData<Resource<NetworkInformation>> networkInfoObservable;
  private final APIClient apiClient;

  @Inject
  NetworkInformationViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;
    getNetworkInformation();
  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInfoObservable;
  }

  // making API calls and adding it to Observable
  public void getNetworkInformation() {
    networkInfoObservable = apiClient.getNetworkInformation();
  }
}

In Activity, the ViewModel is defined as followed -

final NetworkInformationViewModel networkInformationViewModel =
      ViewModelProviders.of(this, viewModelFactory).get(NetworkInformationViewModel.class);
    observeViewModel(networkInformationViewModel);

The observeViewModel function is used to add observable on ViewModel.

public void observeViewModel(final NetworkInformationViewModel networkInformationViewModel) {
    networkInformationViewModel.getNetworkInfoObservable()
      .observe(this, networkInformationResource -> {
        if (networkInformationResource != null) {
          if (networkInformationResource.status == APIClientStatus.Status.SUCCESS) {
            Timber.d("Got network information data");
          } else {
            final Throwable throwable = networkInformationResource.throwable;
            if (throwable instanceof SocketTimeoutException) {
              final NetworkInformation networkInformation = networkInformationResource.data;
              String error = null;
              if (networkInformation != null) {
                error = TextUtils.isEmpty(networkInformation.error) ? networkInformation.reply : networkInformation.error;
              }
              Timber.e("Timeout error occurred %s %s", networkInformationResource.message, error);

            } else {
              Timber.e("Error occurred %s", networkInformationResource.message);
            }
            if (count != 4) {
              networkInformationViewModel.getNetworkInformation();
              count++;
              // Uncommenting following line enables callback to be received every time 
              //observeViewModel(networkInformationViewModel);
            }
          }
        }
      });
  }

Uncommenting the following line in above function allows the callback to come everytime, but there has to be a proper way of doing this.

//observeViewModel(networkInformationViewModel);

Please note:- I don't need RxJava implementation for implementing this.

like image 895
Rohan Kandwal Avatar asked Nov 28 '17 07:11

Rohan Kandwal


People also ask

How to observe LiveData?

Attach the Observer object to the LiveData object using the observe() method. The observe() method takes a LifecycleOwner object. This subscribes the Observer object to the LiveData object so that it is notified of changes. You usually attach the Observer object in a UI controller, such as an activity or fragment.

Can LiveData have multiple observers?

LiveData is amazing android architectural component for most of use cases where we need to fetch data from some data source.

Is ViewModel lifecycle aware?

Lifecycle Awareness :Viewmodel is lifecycle aware. It is automatically cleared when the lifecycle they are observing gets permanently destroyed.


Video Answer


1 Answers

Right now in getNetworkInformation() you are:

  1. Creating a new LiveData
  2. Updating the the LiveData using setValue

Instead, you should have a single LiveData for APIClient created as a member variable, then in getNetworkInformation() just update that member LiveData.

More generally, your APIClient is a data source. For data sources, you can have them contain member LiveData objects that update when the data changes. You can provide getters to those LiveData objects to make them accessible in ViewModels, and ultimately listen to them in your Activities/Fragments. This is similar how you might take another data source, such as Room, and listen to a LiveData returned by Room.

So the code in this case would look like:

@Singleton
public class APIClient {
    private final MutableLiveData<Resource<NetworkInformation>> mNetworkData = new MutableLiveData<>(); // Note this needs to be MutableLiveData so that you can call setValue

    // This is basically the same code as the original getNetworkInformation, instead this returns nothing and just updates the LiveData
    public void fetchNetworkInformation() {
        apiInterface.getNetworkInformation().enqueue(new Callback<NetworkInformation>() {
          @Override
          public void onResponse(
            @NonNull Call<NetworkInformation> call, @NonNull Response<NetworkInformation> response
          ) {
            if (response.body() != null && response.isSuccessful()) {
              mNetworkData.setValue(new Resource<>(APIClientStatus.Status.SUCCESS, response.body(), null));
            } else {
              mNetworkData.setValue(new Resource<>(APIClientStatus.Status.ERROR, null, response.message()));
            }
          }

          @Override
          public void onFailure(@NonNull Call<NetworkInformation> call, @NonNull Throwable throwable) {
            mNetworkData.setValue(
              new Resource<>(APIClientStatus.Status.ERROR, null, throwable.getMessage(), throwable));
          }
        });
    }

    // Use a getter method so that you can return immutable LiveData since nothing outside of this class will change the value in mNetworkData
    public LiveData<Resource<NetworkInformation>> getNetworkData(){
        return mNetworkData;
    }

}

Then in your ViewModel...

// I don't think this should be a Singleton; ViewModelProviders will keep more than one from being instantiate for the same Activity/Fragment lifecycle
public class SplashScreenViewModel extends AndroidViewModel {

private LiveData<Resource<NetworkInformation>> networkInformationLiveData;

  @Inject
  SplashScreenViewModel(@NonNull APIClient apiClient, @NonNull Application application) {
    super(application);
    this.apiClient = apiClient;

    // Initializing the observable with empty data
    networkInfoObservable = apiClient.getNetworkData()

  }

  public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
    return networkInformationLiveData;
  }

}

Your activity can be the same as you originally coded it; it will just get and observe the LiveData from the ViewModel.

So what is Transformations.switchMap for?

switchMap isn't necessary here because you don't need to change the underlying LiveData instance in APIClient. This is because there's really only one piece of changing data. Let's say instead your APIClient needed 4 different LiveData for some reason, and you wanted to change which LiveData you observed:

public class APIClient {
    private MutableLiveData<Resource<NetworkInformation>> mNetData1, mNetData2, mNetData3, mNetData4;

    ...
}

Then let's say that your fetchNetworkInformation would refer to different LiveData to observe depending on the situation. It might look like this:

public  LiveData<Resource<NetworkInformation>> getNetworkInformation(int keyRepresentingWhichLiveDataToObserve) {
    LiveData<Resource<NetworkInformation>> currentLiveData = null;
    switch (keyRepresentingWhichLiveDataToObserve) {
        case 1:
            currentLiveData = mNetData1; 
            break;
        case 2:
            currentLiveData = mNetData2; 
            break;
        //.. so on
    }

    // Code that actually changes the LiveData value if needed here

    return currentLiveData;
}

In this case the actual LiveData coming from getNetworkInformation is changes, and you're also using some sort of parameter to determine which LiveData you want. In this case, you'd use a switchMap, because you want to make sure that the observe statement you called in your Activity/Fragment observes the LiveData returned from your APIClient, even if you change the underlying LiveData instance. And you don't want to call observe again.

Now this is a bit of an abstract example, but it's basically what your calls to a Room Dao do -- if you have a Dao method that queries your RoomDatabase based on an id and returns a LiveData, it will return a different LiveData instance based on the id.

like image 125
Lyla Avatar answered Nov 09 '22 19:11

Lyla