发生错误时如何处理项目?

考虑以下代码:


    Collection<String> foos = Arrays.asList("1", "2", "3", "X", "5", "6", "7", "8", "9", "10");


    Flowable<Integer> integerFlowable = Flowable.fromIterable(foos).map(s -> Integer.parseInt(s)).onErrorReturnItem(-1);


    PublishProcessor<Integer> processor = PublishProcessor.create();

    processor.map(i -> 2 * i).subscribe(i -> System.out.println(i), e -> System.out.println("error!"));

    integerFlowable.subscribe(processor);

到达“X”时处理结束。


我如何指示 RxJava 继续处理其余的项目?


慕桂英3389331
浏览 61回答 2
2回答

繁华开满天机

如果尝试用给定值(例如 -1)替换所有“无效”输入,您可以提供不同的映射器函数。Flowable<Integer> integerFlowable = Flowable.fromIterable(foos)&nbsp; &nbsp; .map(s -> {&nbsp; &nbsp; &nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return Integer.parseInt(s);&nbsp; &nbsp; &nbsp; &nbsp; } catch (NumberFormatException e) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return -1;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });您还可以在创建 Flowable 之前删除所有“无效”输入。Collection<String> foos = Arrays.asList("1", "2", "3", "X", "5", "6", "7", "8", "9", "10");Collection<String> numbers = foos.stream().filter(s -> {&nbsp; &nbsp; try {&nbsp; &nbsp; &nbsp; &nbsp; Integer.parseInt(s);&nbsp; &nbsp; &nbsp; &nbsp; return true;&nbsp; &nbsp; } catch (NumberFormatException e) {&nbsp; &nbsp; &nbsp; &nbsp; return false;&nbsp; &nbsp; }}).collect(Collectors.toList());

慕娘9325324

通常,调用层次结构中的上层方法应该以有用的方式处理异常(不仅仅是捕获)。通常这意味着向用户显示有用的错误消息。对于您的用例,检查字符串是否为数字就足够了:if&nbsp;(s.matches("-?\\d+"))&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;Integer.parseInt(s) &nbsp;&nbsp;&nbsp;&nbsp;}这是一个基本示例,可能不会涵盖您的所有用例(例如前导零或溢出之类的东西)。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java