Observing Changes In Room Database Table Using Itemkeyeddatasource
I have implemented class which extends ItemKeyedDataSource and provides paging data from room database's data access object (DAO). My DAO's query methods pass lists of data objects
Solution 1:
Automatic DataSource
invalidation can be implemented by hooking InvalidationTracker.Observer
to InvalidationTracker
.
You can get InvalidationTracker
instance from getInvalidationTracker().
I implemented my InvalidationTracker.Observer
like this:
publicclassDataSourceTableObserverextendsInvalidationTracker.Observer {
privateDataSource dataSource;
publicDataSourceTableObserver(@NonNullString tableName) {
super(tableName);
}
@OverridepublicvoidonInvalidated(@NonNullSet<String> tables) {
if (dataSource != null) dataSource.invalidate();
}
publicvoidsetCurrentDataSource(DataSource source) {
dataSource = source;
}
}
And I'm using it in my inner DataSource.Factory
class like this:
publicstaticclassFactoryimplementsDataSource.Factory<TvProgram, TvProgram> {
private Context appContext;
private DataSourceTableObserver observer;
private InvalidationTracker tracker;
privateint channelId;
publicFactory(Context context, int channelId) {
appContext = context.getApplicationContext();
observer = new DataSourceTableObserver(AppDatabase.PROGRAMS_TABLE);
tracker = AppDatabase.getInstance(appContext).getInvalidationTracker();
tracker.addObserver(observer);
this.channelId = channelId;
}
@Override
public DataSource<TvProgram, TvProgram> create() {
EpgDataSource epgDataSource = new EpgDataSource(appContext, channelId);
observer.setCurrentDataSource(epgDataSource);
return epgDataSource;
}
publicvoidcleanUp() {
tracker.removeObserver(observer);
observer = null;
}
}
When DataSourceTableObserver
invalidates DataSource
, it's Factory
inner class creates new DataSource
instance with newest data.
Post a Comment for "Observing Changes In Room Database Table Using Itemkeyeddatasource"