我想通過名稱從文件中檢索特定的城市。如果未找到該城市,則返回Observable.empty();否則我會返回Observable.just(城市); 下面是代碼:RxJava:在Observable.just之後它仍然調用Observable.empty()
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();
});
}
但是,當城市發現的問題是,它去return Observable.empty();
我不知道爲什麼它返回Observable.just(city);
。所以代碼() -> view.showCouldNotFindCity()
被稱爲無論如何。
除非出現錯誤,'view.showCouldNotFindCity()'將始終被調用。這不是你想要的嗎? – Will
@但我想要有兩個選擇:如果找到了城市,並且沒有找到城市。代碼根據rusult而不同。什麼是最好的方式來做到這一點? – alla