RxJava:在Observable之后。它仍然调用Observable.empty()

时间:2016-09-26 08:44:59

标签: java android rx-java rx-android

我想通过名称从文件中检索特定城市。如果找不到这个城市,我会返回Observable.empty();否则我返回Observable.just(city); 这是代码:

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

        subscriptions.add(subscription);
    }

方法getCity()

public Observable<City> getCity(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(); 
        });
    }

但问题是当城市被找到并且它返回Observable.just(city);时它会转到return Observable.empty();我不知道为什么。所以无论如何都要调用代码() -> view.showCouldNotFindCity()

1 个答案:

答案 0 :(得分:1)

问题是你打电话给这个() - &gt; onCompleted处理程序中的view.showCouldNotFindCity()。如果您查看RxJava中的just()方法,您会看到它首先调用onNext,然后调用onCompleted方法。所以当城市被发现时 - &gt; view.cityExists()被调用,然后立即调用() - &gt; view.showCouldNotFindCity()。

如果在你的getCity方法中找不到city,我会抛出一个错误。由于你的onError已经调用了desired() - &gt; view.showCouldNotFindCity()方法并从onCompleted处理程序中删除它。