[英]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>>
(從Dao返回),而不是列表本身。 這樣,您可以觀察實時數據並在基礎數據每次更新時收到警報
可以在這里找到文檔: https : //developer.android.com/topic/libraries/architecture/livedata
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.