Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the use case for doOnSuccess vs onSuccess in rxJava

I'm confusing about use case for doOnSuccess in rxJava.
Let's see the code:

Case 1:

networkApi.callSomething()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())               
    .doOnSuccess(__ -> showLog(SUCCESS))
    .doOnError(__ -> showLog(ERROR))
    .subscribeBy(
             onSuccess = {//Do something}, 
             onError = {//Show log here}
          )

Case 2:

networkApi.callSomething()
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())               
    .subscribeBy(
             onSuccess = {
               //Do something
               showLog(SUCCESS)
             }, 
             onError = {showLog(ERROR)}
          )

As normal, I think case 2 is fine.
I also have referred some source code in github and I saw some people do like case 1.
I try to ask myself what is the use case for doOnSuccess here ?

Is there any use case that we need apply doOnSuccess() operator ?

like image 577
Bulma Avatar asked Mar 15 '19 02:03

Bulma


1 Answers

Singles and Maybes have a success signal and the handler has the onSuccess method called. Often though, you'd want to side-effect the success signal at various points in the flow so there is the doOnSuccess operator.

getUserAsSingle()
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess(user -> ui.showUser(user))
.flatMap(user -> 
     getUserFavoritesAsSingle(user)
     .subscribeOn(Schedulers.io())
)
.observeOn(AndroidSchedulers.mainThread())
.doOnSuccess(userFavs -> ui.showUserFavorites(userFavs))
.flatMap(userFavs -> 
     updateLoginCounter(userFavs.userId)
     .subscribeOn(Schedulers.io())
)
.observeOn(AndroidSchedulers.mainThread())
subscribe(newCounter -> ui.showLoginCount(newCounter),
    error -> ui.showError(error));
like image 103
akarnokd Avatar answered Sep 19 '22 17:09

akarnokd