如何知道 Room 数据库操作何时完成?

How to know when Room database operations are done?

我是第一次使用 Room,我注意到在操作完成时似乎没有任何回调。这存在吗?如果不是,插入或更新数据然后立即检索该数据的最佳做法是什么。我想要保证所做的更改。我注意到,除非我在检索数据之前有任意延迟,否则我得到的数据是旧数据而不是更新数据。

这是一个 DAO 示例

@Dao
public interface TestDao {

    @Query("SELECT * FROM test_table")
    List<TestEntity> getAll();

    @Query("DELETE FROM test_table")
    void deleteAll();

    @Insert
    void insert(TestEntity testEntities);

    @Delete
    void delete(TestEntity testEntity);

    @Update
    void update(TestEntity testEntity);
}

这是我的 AppDatabase

@Database(entities = {TestEntity.class}, version = 1, exportSchema = false)
public abstract class AppDatabase extends RoomDatabase {

    private static final String DATABASE_NAME = "room.test.db";
    private static AppDatabase APP_DATABASE_INSTANCE;

    public abstract TestDao testDao();

    public static AppDatabase getAppdatabase(@NonNull Context context) {
        if (FrameworkUtils.checkIfNull(APP_DATABASE_INSTANCE)) {
            APP_DATABASE_INSTANCE = Room.databaseBuilder(context.getApplicationContext(),
                    AppDatabase.class, DATABASE_NAME).build();
        }
        return APP_DATABASE_INSTANCE;
    }

    /**
     * Method is used to destroy database instance
     */
    public static void destroy() {
        APP_DATABASE_INSTANCE = null;
    }
}

这是我执行更新的方式

Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                // update database tables
                AppDatabase.getAppdatabase(context).testDao().update(testEntity);

            }
        });

这是我检索数据的方式

Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                // get database data
                List<TestEntity> alData = AppDatabase.getAppdatabase(context).testDao().getAll();

            }
        });

我为此代码创建了函数,这样我就可以调用 update(testEntity) 和 get()。问题是我无法进行背靠背操作

TestEntity testEntity = new TestEntity();
testEntity.fname = "firstName"
testEntity.lname = "lastName"

update(testEntity);
get(); // the data fetched is old data unless I wrap this with a 5 second delay or something

您应该使用 LiveData<List<Entity>>(return 它来自 Dao)而不是列表本身。这样您就可以观察实时数据并在每次基础数据更新时收到警报

可在此处找到文档:https://developer.android.com/topic/libraries/architecture/livedata