合并两个可观察对象的正确接收操作

时间:2019-02-25 15:08:27

标签: android rx-java android-room rx-android

我写了下面的类来访问我的仓库,包括远程仓库和本地仓库。

public class VenuesRepoImpl implements VenuesRepo {

private VenuesLocalRepo venuesLocalRepo;
private VenuesRemoteRepo venuesRemoteRepo;

public VenuesRepoImpl(VenuesLocalRepo venuesLocalRepo, VenuesRemoteRepo venuesRemoteRepo) {
    this.venuesLocalRepo = venuesLocalRepo;
    this.venuesRemoteRepo = venuesRemoteRepo;
}

@Override
public Observable<List<Venue>> getAllVenues(String ll, int offset) {
    return Observable.merge(venuesRemoteRepo.getAllVenues(ll, offset)
                    .doOnNext(venues -> venuesLocalRepo.addVenues(venues)).subscribeOn(Schedulers.io()),
            venuesLocalRepo.getAllVenues().subscribeOn(Schedulers.io()));
}



@Override
public void deleteAllVenues() {
    Completable.fromAction(() -> venuesLocalRepo.deleteAll()).subscribeOn(Schedulers.io());

}

}

但是Observable.merge复制了我的项目,它同时具有api和db项目。当api不可用时,如何访问数据库项目?

1 个答案:

答案 0 :(得分:2)

您应该使用concat()而不是merge()

您可以遵循以下模式:

// Our sources (left as an exercise for the reader)
Observable<Data> memory = ...;
Observable<Data> disk = ...;
Observable<Data> network = ...;

// Retrieve the first source with data
Observable<Data> source = Observable
  .concat(memory, disk, network)
  .first();

更多信息here