在执行自定义SQL查询ROOM时通知观察者 [英] Notify observers when executing a custom sql query ROOM

查看:112
本文介绍了在执行自定义SQL查询ROOM时通知观察者的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试寻找一种方法来通知Roomroom数据库中的数据是否已更改的当前活动观察者.我所有的数据都包装在LiveData观察器对象中,然后在它们上附加了一个观察器.

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.

这是基本的道教之一.

@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);

}

我从服务器接收SQL字符串查询,然后根据文档执行它们的唯一方法是:

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);

那么我如何使其与观察者一起工作?如何通知或让他们无效以重新加载ui?

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

推荐答案

您需要将 refreshVersionsAsync()与Room的 InvalidationTracker 一起使用.

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

这实际上是检查是否有任何表已更改,并通知所有更改有关的回调,从而使实时数据能够在您的UI中刷新.

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.

确保使用 execSQL 执行的SQL查询不会重新创建表,因为销毁表时跟踪概念会丢失.如果需要重新创建表,请使用 clearAllTables()擦除所有数据,但重要的是不要擦除表本身,然后使用SQL查询重新插入记录.

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.

API参考:

使任务排队以刷新已更新表的列表.调用RoomDatabase.endTransaction()时会自动调用此方法,但是如果您与数据库有另一个连接或直接使用SupportSQLiteDatabase,则可能需要手动调用此方法.

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.

这篇关于在执行自定义SQL查询ROOM时通知观察者的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆