首页 > 解决方案 > 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?

标签: javaspringjava-8rx-javaflux

解决方案


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

enter image description here

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.


推荐阅读