Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if RoomDatabase is empty while using LiveData

I am trying to use RoomDatabase in my Android App. And I am using LiveData to be able to refresh my changes automatically inside my fragment.

The first time I am running my app I am getting the data from the API, creating my RoomDatabase and storing my data.

The second time I run my app I want to check if my DataBase is not empty. But while using LiveData: the following code is returning null.

AppDatabase.getInstance(getContext()).getRecipeDao().getAllRecipes().getValue();

I have read that "if the response is an observable data type, such as Flowable or LiveData, Room watches all tables referenced in the query for invalidation".

How to check if my RoomDatabase has data or is empty?

like image 571
yalematta Avatar asked Feb 06 '18 22:02

yalematta


1 Answers

So after implementing myself I found that you need to do a few things:

  1. Make sure you have an Observer for changes to the LiveData
  2. You need to call observeForever(Observer<T> observer) unless you are using a LiveCyclerOwner then use that instead with: observe (LifecycleOwner owner, Observer<T> observer)
  3. Finally, there is an interesting note on getValue():

Returns the current value. Note that calling this method on a background thread does not guarantee that the latest value set will be received

So to reiterate, I think your approach does not work.

You will need to create some type of separate check rather than use a method that returns a LiveData class as noted since it does not guarantee the latest value set is received by calling getValue().

I would recommend something super simple in the end such as adding a new method to your Dao

@Query("SELECT * FROM recipes LIMIT 1")
Recipe getAnyRecipe();

and do this check looking for null to see if anything exists in the recipes table.

like image 180
kandroidj Avatar answered Oct 19 '22 01:10

kandroidj