java - Difference between doOnSuccess and doOnEach, and in which use case i should use each of them
问题描述
I am reviewing a source code file and found in certain commit that we changed the usage of
.doOnSuccess(response -> logBodyAsJSON(response ));
Into
.doOnEach(response -> logBodyAsJSON(response ));
I cannot find a clear reason to do that.
So what is the difference between doOnSuccess and doOnEach, and in which use case i should use each of them?
解决方案
doOnSuccess
will, as its name implies, only be called when your observable returns an item successfully, and doesn't raise an error. As such, you will only log the confirmation responses.
Also, doOnSuccess works for Singles or Maybes, which can only emit a single item (you would use doOnNext otherwise). If you use an Observable which can emit multiple items, you'd use doOnNext
to have the exact same behaviour.
doOnEach
will be called whether the observable emits an item, error or not. It receives a Notification instead of the item itself. It will be called:
- onSuccess and onError for a Single
- onNext, onComplete and onError for a typical Observable
It's highly likely that the observable item changed from a Single to an Observable. Also, there would exist a need to be able to log errors as well as successes, which is why doOnNext
wasn't chosen.
推荐阅读
- java - 什么会启动 Connection evictor 线程以及如何避免这些线程累积?
- prism - Theme-ui/prism 不适用于 gatsbyjs 降价文件
- flutter - Flutter有状态小部件导入找不到功能
- r - 在新列中获取所有 NA [变异]
- java - 是否可以在 java 中使用 RabbitMQ 从配置中创建多个队列和交换?
- python - 玩家在pygame中没有移动
- angular - “typeof ExampleService”类型中缺少属性“save”,但在“ExampleAbstractClassService”类型中是必需的
- javascript - 调整窗口大小时如何使div不缩小?
- mainframe - 如何在 ISPF 中滚动到顶部?
- sql - 当数据类型为整数时,如何按日期对 BigQuery 中的表进行分区?