我搜索城市,如果它不存在,我想做一个与城市存在的情况不同的行为。RxJava:条件代码
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(),但它不完全是我想要的,如果城市== null,它就不会更进一步。 你可以请一些更好的主意建议吗?
什么时候我把情况view.cityExists()方法中的城市被发现?它会以同样的方法成为另一个可观察对象吗? – alla
因此,在结果中,我不明白如何使用switchIfEmpty()(我会更详细地阅读它),但我喜欢这个想法返回Observable.error(e);或Observable.empty(); ,所以在onAddButtonClick()我在subscribe()方法中添加了以下代码: 'throwable - > view.showCouldNotFindCity()', '() - > view.showCouldNotFindCity()' – alla