I am working with Room for the first time and notice that there doesn't seem to be any callbacks for when an operation is finished being performed. Does this exist? If not, what is the best practice for inserting or updating data and then immediately retrieving that data. I want a guarentee that the changes were made. I am noticing that unless I have an arbitrary delay before retrieval the data I am getting is old data and not the update data.
Here is an example 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);
}
Here is my 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;
}
}
Here is how I am performing updates
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// update database tables
AppDatabase.getAppdatabase(context).testDao().update(testEntity);
}
});
Here is how I am retrieving my data
Thread t = new Thread(new Runnable() {
@Override
public void run() {
// get database data
List<TestEntity> alData = AppDatabase.getAppdatabase(context).testDao().getAll();
}
});
I created functions for this code so that I can just do call update(testEntity) and get(). The problem is that I am unable to do back to back operations
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