Room Flowable不会在插入

时间:2017-12-26 09:54:49

标签: android rx-java2 android-room android-database android-architecture-components

我很难理解Flowable在Room中的运作方式。我有Dao这样的方法

@Insert(onConflict = OnConflictStrategy.REPLACE)
void upsert(List<Site> sites);

@Query("SELECT * FROM site ORDER BY distance ASC")
Flowable<List<Site>> getSites();

我希望每当我调用upsert时,Flowable返回的getSites()对象将始终被调用。我的假设是真的吗?

以下是我对这个流动的

的描述
private final Flowable<List<Site>> siteFlowable;
ApiService apiService;
FuelDatabase database;

@Override
public void getSites(boolean showOnlyKeySites) {
    // add sites from cache first, then fetch network -> update cache -> update ui
    disposable = siteFlowable.flatMap(Flowable::fromIterable)
        .filter(site -> site.isValid())
        .buffer(100, TimeUnit.MILLISECONDS, 20)
        .takeUntil(sites -> sites.size() == 0)
        .observeOn(AndroidSchedulers.mainThread())
        .doOnNext(mapView::addPins)
        .subscribe(sites -> {
            Timber.d("Flowable emitted %d items", sites.size());
        }, Timber::e);

    apiService.getSites()
        .map(SiteListResponse::getData)
        .flatMap(Observable::fromIterable)
        .filter(Site::isValidSite)
        .toList().toObservable()
        .subscribe(sites -> {
            Timber.i("Success Fetching %d sites", sites.size());
            database.siteDao().clear();
            database.siteDao().upsert(sites);
        }, throwable -> Timber.e(throwable, "Error fetching sites"));
}

调用upsert()后,不会调用此可流动的内容。 API返回有效数据,数据将输入数据库。

1 个答案:

答案 0 :(得分:-1)

试试这个:

apiService.getSites()
    .map(SiteListResponse::getData)
    .flatMap(result -> 
         Observable.fromIterable(result)
        .filter(Site::isValidSite)
        .toList()
        .toFlowable()
    )
    .subscribe(sites -> {
        Timber.i("Success Fetching %d sites", sites.size());
        database.siteDao().clear();
        database.siteDao().upsert(sites);
    }, throwable -> Timber.e(throwable, "Error fetching sites"));