0

I've been trying to find a way to notify currently active observers if data in Room database has changed. All my data is wrapped in LiveData observer objects and then they have an observer attached to them.

This is one of the basic Daos.

@Dao
public interface SubcategoryDao {

    @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertSubcategory(Subcategory... subcategories);

    @Query("SELECT * FROM subcategory_table")
    LiveData<List<Subcategory>> getAllSubcategories();

    @Query("SELECT * FROM subcategory_table WHERE category_id=:catId")
    LiveData<List<Subcategory>> getAllSubcategoriesForCategory(int catId);

    @Query("SELECT id FROM subcategory_table WHERE title=:title")
    LiveData<Integer> getSubcategoryIdByTitle(String title);

    @Query("SELECT * FROM subcategory_table WHERE title=:title")
    LiveData<Subcategory> getSubcategoryByTitle(String title);

}

I am receiving SQL string queries from server and then the only way to execute them according to documentation is this:

AppDatabase.getInstance(activity)
                .getOpenHelper()
                .getWritableDatabase()
                .execSQL(sqlQuery);

So how do I make it work with observers? How do I notify or invalide them to reload ui?

tojetoho
  • 55
  • 1
  • 8

1 Answers1

2

You'll need to use refreshVersionsAsync() with Room's InvalidationTracker.

This essentially checks if any tables have changed and notifies the callbacks around any changes – enabling the Live Data to be refreshed within your UI.

Make sure that the SQL queries you're executing with execSQL aren't recreating tables as the tracking concept is lost when the tables are destroyed. If you need to recreate the tables, use clearAllTables() to wipe any data – but importantly not the table itself – and then reinsert the records with your SQL queries.

From the API Reference:

Enqueues a task to refresh the list of updated tables. This method is automatically called when RoomDatabase.endTransaction() is called but if you have another connection to the database or directly use SupportSQLiteDatabase, you may need to call this manually.

Patrick
  • 855
  • 8
  • 12