RxJava:具有条件的代码

时间:2016-09-23 09:18:51

标签: java android rx-java rx-android

我搜索城市,如果它不存在,我想做一个与城市存在时的情况不同的行动。

public void onAddButtonClick(String cityName) {
        Subscription subscription = repository.getCity(cityName)
                .filter(city -> city != null)
                .subscribeOn(backgroundThread)
                .flatMap(city -> repository.saveCityToDb(city))
                .observeOn(mainThread)
                .subscribe(city -> view.cityExists());

        subscriptions.add(subscription);
}

getCity()方法:

public Observable<City> getCity(String name){
        return fileRepository.getCityFromFile(name);
    }

getCityFromFile()

public Observable<City> getCityFromFile(String cityName){
        try {
            InputStream is = assetManager.open(FILE_NAME);
            Scanner scanner = new Scanner(is);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (line.toLowerCase().contains(cityName.toLowerCase())) {
                    String[] cityParams = line.split("\t");
                    City city = new City();
                    city.setId(Long.parseLong(cityParams[0]));
                    city.setName(cityParams[1]);
                    return Observable.fromCallable(() -> city);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Observable.fromCallable(() -> null);
    }

因此,当找不到城市时,我想向用户发出警报,当找到城市时我想要更进一步(将其保存到数据库,打开主屏幕等)。我使用了运算符过滤器(),但它并不完全是我想要的,如果城市== null,它就不会更进一步。 你能就一些更好的想法提出建议吗?

2 个答案:

答案 0 :(得分:2)

您可以使用Observable.error()抛出错误,并使用Subsriber的{​​{1}}方法捕获它。:

onError()

答案 1 :(得分:2)

这取决于您设计代码的方式。

如果您搜索某个城市但未找到该城市,则可能会返回Observable.empty。或者返回Observable.error(如果是错误的话)。然后,如果为空/错误Observable,则可以使用其他Observable

例如:

    Observable<City> observableIfNoCity = /** observable with perform actions when where is no city */
    repository.getCity(wrongCity) // return an Observable.empty if no city
              .flatMap(city -> repository.saveCityToDb(city))
              .doOnNext(city -> view.cityExists())
              .switchIfEmpty(observableIfNoCity)
              .subscribe();

如果您返回Observable.error,则可以使用onErrorResumeNext代替switchIfEmpty

但为了正确行事,我认为你应该避免在null中发出getCityFromFile值。请改用emptyerror

 public Observable<City> getCityFromFile(String cityName){
      return Observable.defer(() -> {
         try {
            InputStream is = assetManager.open(FILE_NAME);
            Scanner scanner = new Scanner(is);
            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                if (line.toLowerCase().contains(cityName.toLowerCase())) {
                    String[] cityParams = line.split("\t");
                    City city = new City();
                    city.setId(Long.parseLong(cityParams[0]));
                    city.setName(cityParams[1]);
                    return Observable.just(city);
                }
            }
        } catch (IOException e) {
             return Observable.error(e);
        }

        return Observable.empty(); // or Observable.error(new NotFoundException());
    });
}