RxJava:带有条件的代码

RxJava: code with the condition

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

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);
    }

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

您可以使用 Observable.error() 抛出一个错误并在 SubsriberonError() 方法中捕获它。:

Subscription subscription = Observable.just("String")
            .flatMap(city -> city == null ? Observable.error(new NullPointerException("City is null")) : Observable.just(city))
            .subscribeOn(backgroundThread)
            .flatMap(city -> repository.saveCityToDb(city))
            .observeOn(mainThread)
            .subscribe(city -> view.cityExists(),
                    throwable -> view.showError());

这取决于您如何设计代码。

如果您搜索一个城市但没有找到,可能 return 一个 Observable.empty。或 return 一个 Observable.error 代替(如果是错误情况)。然后,在 empty/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();

如果你 return 一个 Observable.error,你可以使用 onErrorResumeNext 而不是 switchIfEmpty

但为了正确运行,我认为您应该避免在 getCityFromFile 中发出 null 值。使用 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());
    });
}