【发布时间】:2016-09-23 09:18:51
【问题描述】:
我搜索城市,如果它不存在,我想采取与城市存在时不同的行动。
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 就不会更进一步。 你能建议一些更好的主意吗?
【问题讨论】:
标签: java android rx-java rx-android