ViewModel Can't Seem to Observe MutableLiveData - android

I have a repository that sets data like so:
private MutableLiveData<JSONObject> myVocab = new MutableLiveData<>();
public Repo(Context context) {
ExecutorService service = Executors.newSingleThreadExecutor();
service.execute(() -> {
myVocab = jsonReader.readJSONFromAssets(context, "myVocab.json")
});
service.shutdown();
}
public MutableLiveData<JSONObject> getVocab() { return myVocab; }
It correctly reads in json and saves it to myVoc, I've already checked.
I also have a ViewModel that listens to the vocab object and then does stuff with it:
private MediatorLiveData<JSONObject> vocab = new MediatorLiveData<>();
/* CONSTRUCTOR */
public WordsViewModel(#NonNull Application application) {
super(application);
wordsRepository = Repo.getInstance(application);
vocab.addSource(_wordsRepository.getVocab(),
jsonObject -> vocab.setValue(jsonObject));
doStuffWithVocab();
}
However, the observer never gets called (I've put logs in there to check). I've run into this issue with several apps now and can't seem to ever resolve it except through hacks.
Why doesn't my observer work? (It works in MainActivity, just not the ViewModel).

Related

Multiple instances of Livedata observers

I am struggling to find a solution for calling a livedata observer multiple times in one activity and not creating multiple instances of it, this leads to the problem when the database changes I got callbacks from all the instances.
ViewModel
public class RatingsViewModel extends AndroidViewModel {
private RatingsRepository ratingsRepository;
private LiveData<List<Rating>> ratingsList;
public RatingsViewModel(Application application) {
super(application);
ratingsRepository = new RatingsRepository(application);
}
public LiveData<List<Rating>> getRatingsByDate(LocalDate date) {
ratingsList = ratingsRepository.getActivitiesByDate(date);
return ratingsList;
}
Activity
private void getRatingsByDate(LocalDate date) {
ratingsViewModel.getRatingsByDate(date).observe(this, activities -> {
// list populating stuff
});
}
I tried calling hasObserver() but it returns false so I cannot remove the observers.
You should be able to do something like following (in Kotlin but should be easily translatable in to Java if needed)
val dateLiveData: MutableLiveData<Date> = MutableLiveData()
val ratingsList = MediatorLiveData<List<Rating>>().apply {
this.addSource(dateLiveData) {
this.value = ratingsRepository.getActivitiesByDate(dateLiveData.value)
}
}
fun setDate(date: Date) {
dateLiveData.value = date
}
You'd call observe from onCreate() for example in your activity/fragment and then call setDate() when that value changes.

Android Room database ViewModel does not reflect synchronously inserted data

I am having an issue where data that is written to my Room database does not appear in a ViewModel even though I am writing it synchronously.
This is what a log would look like:
com.widget D/WriteActivity: Writing widget data to the database
com.widget D/WriteActivity: Starting the ReadActivity
com.widget D/ReadActivity: Got a new list of 0 objects
Here is the situation:
I have two activities, WriteActivity and ReadActivity. Inside of the ReadActivity I have a ViewModel listening for database changes (that is instantiated in the onCreate method of the Activity):
// observe the widget data
WidgetViewModel widgetViewModel = ViewModelProviders.of(this).get(
WidgetViewModel.class);
widgetViewModel.getAllWidgets().observe(this, new Observer<List<Widget>>() {
#Override
public void onChanged(#Nullable final List<Widget> updatedWidgets) {
Log.d(TAG, "Got a new list of " + updatedWidgets.size() + " objects");
}
});
Inside of the WriteActivity I have code that adds an object to the database on a background thread, then, once it completes, it launches the ReadActivity:
// persist the objects to the room database (doInBackground)
WidgetRepository myObjectRepository = new WidgetRepository(getApplication());
myObjectRepository.insert(myObjects); // myObjects is a list of 5 objects
// load the ReadActivity (onPostExecute)
Intent myIntent = new Intent(WriteActivity.this, ReadActivity.class);
WriteActivity.this.startActivity(myIntent);
Here is my DAO:
#Dao
public interface WidgetDao {
#Query("SELECT * FROM widget_table")
LiveData<List<Widget>> getAll();
#Insert(onConflict = OnConflictStrategy.REPLACE)
void insert(Widget... widgets);
}
My Database:
#Database(entities = {Widget.class}, version = 1, exportSchema = false)
public abstract class WidgetDatabase extends RoomDatabase {
public abstract WidgetDao widgetDao();
private static volatile WidgetDatabase INSTANCE;
static WidgetDatabase getDatabase(final Context context) {
if (null == INSTANCE) {
synchronized (WidgetDatabase.class) {
if (null == INSTANCE) {
INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
WidgetDatabase.class, "widget_database")
.build();
}
}
}
return INSTANCE;
}
}
My repository:
public class WidgetRepository {
private final WidgetDao widgetDao;
private final LiveData<List<Widget>> widgets;
public WidgetRepository(Application application) {
WidgetDatabase db = WidgetDatabase.getDatabase(application);
widgetDao = db.widgetDao();
widgets = widgetDao.getAll();
}
public LiveData<List<Widget>> getWidgets() {
return widgets;
}
public void insert(List<Widget> widgetsToInsert) {
widgetDao.insert(widgetsToInsert.toArray(
new Widget[widgetsToInsert.size()]));
}
My ViewModel:
public class WidgetViewModel extends AndroidViewModel {
private final LiveData<List<Widget>> widgets;
public WidgetViewModel (Application application) {
super(application);
WidgetRepository widgetRepository = new WidgetRepository(application);
widgets = widgetRepository.getWidgets();
}
public LiveData<List<Widget>> getAllWidgets() { return widgets;
}
}
Your issue is that LiveData<List<Widget>> is not being notified.
So, how to update that ?
see below,
Update LiveData objects
LiveData has no publicly available methods to update the stored data.
The MutableLiveData class exposes the setValue(T) and postValue(T)
methods publicly and you must use these if you need to edit the value
stored in a LiveData object. Usually MutableLiveData is used in the
ViewModel and then the ViewModel only exposes immutable LiveData
objects to the observers.
So, changes you can make to your ViewModel:
public class WidgetViewModel extends AndroidViewModel {
private final MutableLiveData<List<Widget>> widgets = new MutableLiveData<List<Widget>>(); // Make it mutable livedata
public WidgetViewModel (Application application) {
super(application);
WidgetRepository widgetRepository = new WidgetRepository(application);
//widgets = widgetRepository.getWidgets();
//use this to update your live data instead,
widgets.setValue(widgetRepository.getWidgets().getValue()); // This will update your live data, use like this for future updates.
}
public LiveData<List<Widget>> getAllWidgets() { return widgets;
}
}
Checkout more from here
I figured out what was happening. It's embarassing... when I asked my question I had a fundamental misunderstanding of how LiveData works. RTFM jeez :)
After I read the documentation I came to a stunning revelation: LiveData is tied to the lifecycle of the activity. In the example I gave I was attempting to access the ViewModel during the onResume of my ReadActivity because I was wanted to make sure that the UI updated properly. Rookie mistake. Like a fool I believed that the Observer callback would only fire when the data encapsulated by the LiveData was modified. In reality, the LiveData callback in the Observer is called when the activity becomes active regardless of whether the data has changed, so there is no need to try to do anything in the onResume lifecycle method manually. Just wait for the onChanged callback of the Observer and update the UI at that time.
App is working great now, thank you to everyone who read my question.

Observe Live Data After Second Live Data

My view Model
declares two live data :
the scenario is getting two methods from the repository so that second live data input arguments dependent on first live data got data
public class ProductViewModel extends AndroidViewModel {
private LiveData<DataWrapper<GetProductQuery.Product>> productLiveData;
private LiveData<DataWrapper<ArrayList<ProductList>>> vendorProductLiveData;
private ProductRepository repository ;
public ProductViewModel(#NonNull Application application) {
super(application);
repository = new ProductRepository();
}
public LiveData<DataWrapper<GetProductQuery.Product>> getProductLiveData(String productId) {
productLiveData = repository.getProduct(productId);
return productLiveData;
}
public LiveData<DataWrapper<ArrayList<ProductList>>> getVendorProductLiveData(int vendorId) {
vendorProductLiveData = repository.getLimitProduct(vendorId);
return vendorProductLiveData;
} }
in Activity i want run second live data after first live data :
viewModel.getVendorProductLiveData(Integer.parseInt(p.getId())).observe(getActivity(), arrayListDataWrapper -> {
ArrayList<ProductList> pList =
arrayListDataWrapper.getData();
});
viewModel.getProductLiveData(id).observe(this, productDataWrapper -> {
p = productDataWrapper.getData();
});
viewModel.getVendorProductLiveData(Integer.parseInt(p.getId())).observe(getActivity(), arrayListDataWrapper -> {
//do logic after get product
});
You should use Transformations.switchMap() to transform your first LiveData to your second LiveData using the former emitted value as the argument. Then you can observe this transformed LiveData to get the final result.

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.
Right now in getNetworkInformation() you are:
Creating a new LiveData
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.
I didn't met the same issue, but i came across a similar thing where the number of observers were increasing each time i was saving the data in db. The way i debugged was how many instances or different instances of observers were getting invoked and i came to know that when you are fetching the live data from view model it needs to be checked for non null or you can say only 1 instance is being returned -
private LiveData<T> data;
public LiveData<T> getLiveData(){
if(data ==null){
data = //api call or fetch from db
}
return data;
}
Before i was simply returning the data object and then after checking the source i came to the conclusion that livedata automatically updates your object and everytime without the null check new instance was getting created and new observers were getting attached. Someone can correct me if my understanding regarding livedata is wrong.
I have already updated the linked question's answer. Re-posting here since I have placed a bounty on the question and hopefully someone will verify that this is the proper way to handle the issue.
Following is the updated working solution -
#Singleton
public class SplashScreenViewModel extends AndroidViewModel {
private final APIClient apiClient;
// This is the observable which listens for the changes
// Using 'Void' since the get method doesn't need any parameters. If you need to pass any String, or class
// you can add that here
private MutableLiveData<Void> networkInfoObservable;
// This LiveData contains the information required to populate the UI
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 = new MutableLiveData<Void>();
// Using the Transformation switchMap to listen when the data changes happen, whenever data
// changes happen, we update the LiveData object which we are observing in the MainActivity.
networkInformationLiveData = Transformations.switchMap(networkInfoObservable, input -> apiClient.getNetworkInformation());
}
/**
* Function to get LiveData Observable for NetworkInformation class
* #return LiveData<Resource<NetworkInformation>>
*/
public LiveData<Resource<NetworkInformation>> getNetworkInfoObservable() {
return networkInformationLiveData;
}
/**
* Whenever we want to reload the networkInformationLiveData, we update the mutable LiveData's value
* which in turn calls the `Transformations.switchMap()` function and updates the data and we get
* call back
*/
public void setNetworkInformation() {
networkInfoObservable.setValue(null);
}
}
The Activity's code will be updated as -
final SplashScreenViewModel splashScreenViewModel =
ViewModelProviders.of(this, viewModelFactory).get(SplashScreenViewModel.class);
observeViewModel(splashScreenViewModel);
// This function will ensure that Transformation.switchMap() function is called
splashScreenViewModel.setNetworkInformation();
Watch her droidCon NYC video for more information on LiveData. The official Google repository for LiveData is https://github.com/googlesamples/android-architecture-components/ look for GithubBrowserSample project.
The apiClient.getNetworkInformation() call doesn't need it any parameters to get additional information. Hence, the 'Void' added in MutableLiveData.
public LiveData<Resource<NetworkInformation>> getNetworkInformation() {
final MutableLiveData<Resource<NetworkInformation>> data = new MutableLiveData<>();
apiInterface.getNetworkInformation().enqueue(new Callback<NetworkInformation>() {
#Override
public void onResponse(
#NonNull Call<NetworkInformation> call, #NonNull Response<NetworkInformation> response
) {
if (response.body() != null && response.isSuccessful()) {
data.setValue(new Resource<>(APIClientStatus.Status.SUCCESS, response.body(), null));
} else {
data.setValue(new Resource<>(APIClientStatus.Status.ERROR, null, response.message()));
}
}
#Override
public void onFailure(#NonNull Call<NetworkInformation> call, #NonNull Throwable throwable) {
data.setValue(
new Resource<>(APIClientStatus.Status.ERROR, null, throwable.getMessage(), throwable));
}
});
return data;
}

Making changes to LiveData to "redo" work in ViewModel

So, I have just started experimenting with LiveData - I am busy with a new project, where I am using ViewModel as well as LiveData - with some of the RESTFul services I use to fetch data, they take no parameters and return some data.
A typical setup of the MVVM paradigm with LiveData looks much like this:
public class MyActivity extends AppCompatActivity {
public void onCreate(Bundle savedInstanceState) {
MyViewModel model = ViewModelProviders.of(this).get(MyViewModel.class);
model.getUsers().observe(this, users -> {
// update UI
});
}
}
Now when we leave this activity, and go to a new activity, by using an Intent or some other means, and not pressing the back button (So, finalize is not called) - and then come back to MyActivity - we of course don't fetch the users again, as we should still have that data.
However, what if we did want to fetch them again?
The only way to do this properly, from what I have looked at, seems to call "setValue" on the getUsers() LiveData object
Something like this:
public class MyActivity extends AppCompatActivity {
public void onResume() {
viewModel.setActive(true);
}
}
And the ViewModel would look like this:
private final MutableLiveData<Boolean> activeLiveData = new MutableLiveData<>();
ViewModel(ViewModelRepo repo){
this.repo = repo;
results = Transformations.switchMap(activeLiveData, active ->{
if(active){
return repo.getUsers();
}else {
return AbsentLiveData.create(); //"Null live data"
}
});
}
LiveData<Users>> getUsers() {
return results;
}
//This could be called "update" with no params
void setActive(boolean active) {
activeLiveData.setValue(active);
}
The one reason I have decided to do it like this is because Google does not want us doing this:
class MyViewModel extends ViewModel {
private final PostalCodeRepository repository;
public MyViewModel(PostalCodeRepository repository) {
this.repository = repository;
}
private LiveData<String> getPostalCode(String address) {
// DON'T DO THIS
return repository.getPostCode(address);
}
}
For this reason:
If this is the implementation, the UI would need to unregister from
the previous LiveData and re-register to the new instance each time
they call getPostalCode(). Moreover, if the UI is re-created, it
triggers another call to repository.getPostCode() instead of using the
previous call’s result.
Is there a better way to get the ViewModel to "redo" its repo.getUsers() call? Perhaps I could just make a method that says "Update()" instead of "active" but still - its doing the same thing differently.
Well here you're doing the fetching in the creator of the ViewModel, which locks things in place. Usually they'd advise to fetch the data in the getter, if the data is not there already.
So a good option would be to use the regular pattern first :
private MutableLiveData<Users> users = null;
ViewModel(ViewModelRepo repo){
this.repo = repo;
}
LiveData<Users> getUsers() {
if (users = null) {
fetchUsers();
}
return users;
}
public void fetchUsers() {
users.postValue(repo.getUsers());
}
And then from your Activity/Fragment, whenever you feel necessary to "refresh the users", you'd simply call viewModel.fetchUsers();

Categories

Resources