我正在显示使用翻新和Room数据源的PagedList。当我仍在首页上时,如何搜索整个列表。
我尝试用Room搜索。但是无法获取尚未添加到数据库的项目。
这是我的资料库
public class ItemsRepository {
private static final String TAG = "ItemsRepository";
private static ItemsRepository instance;
final private ItemsNetwork network;
final private ItemsDatabase database;
final private MediatorLiveData liveDataMerger;
public ItemsRepository(Context context) {
NetItemsDataSourceFactory dataSourceFactory = new NetItemsDataSourceFactory(context);
network = new ItemsNetwork(dataSourceFactory, boundaryCallBack);
database = ItemsDatabase.getInstance(context.getApplicationContext());
// When we get new Items from network we set them into the database
liveDataMerger = new MediatorLiveData();
liveDataMerger.addSource(network.getPagedItems), value -> {
liveDataMerger.setValue(value);
});
// Save Items into DB
dataSourceFactory.getItems().
observeOn(Schedulers.io()).
subscribe(item -> {
((ItemsDatabase) database).itemsDao().insertItems(item);
});
}
private PagedList.BoundaryCallback<Item> boundaryCallBack = new PagedList.BoundaryCallback<Item>() {
@Override
public void onZeroItemsLoaded() {
super.onZeroItemsLoaded();
liveDataMerger.addSource(database.getPagedItems(), value -> {
liveDataMerger.setValue(value);
liveDataMerger.removeSource(database.getPagedItems());
});
}
};
public static ItemsRepository getInstance(Context context) {
if (instance == null) {
instance = new ItemsRepository(context);
}
return instance;
}
public LiveData<NetworkState> getNetworkState() {
return network.getNetworkState();
}
public LiveData<PagedList<Items>> getItems() {
return liveDataMerger;
}
}
我不确定什么是最好的方法,先从网络查询然后更新项目或直接查询Room db