Reputation: 549
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.
Upvotes: 0
Views: 517
Reputation: 1101
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.
Upvotes: 1