简体   繁体   中英

RxJava: After Observable.just it still calls Observable.empty()

I want to retrieve particular city from a file by its name. If the city isn't found I return Observable.empty(); Otherwise I return Observable.just(city); Here is the code:

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

And method 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(); 
        });
    }

But the problem is when the city is found and it returns Observable.just(city); it goes to return Observable.empty(); I don't know why. So the code () -> view.showCouldNotFindCity() is called anyway.

The problem is that you call this () -> view.showCouldNotFindCity() in onCompleted handler. If you take a look at the just() method in RxJava you'll see that it calls first onNext and then onCompleted methods on subscriber. So when city is found city -> view.cityExists() gets called and then immediately after () -> view.showCouldNotFindCity().

I would just throw an error if city is not found in your getCity method. Since your onError already calls desired () -> view.showCouldNotFindCity() method and remove it from onCompleted handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM