8

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 ?

Bulma
  • 990
  • 3
  • 16
  • 35
  • doOnSuccess is a Disposable CallBack Method on the other hand onSuccess is Lamda Expression of doOnSuccess from subscribeBy. – aslamhossin Mar 15 '19 at 03:08

2 Answers2

10

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));
akarnokd
  • 69,132
  • 14
  • 157
  • 192
1

One use case I normally apply for doOnSuccess() is to enforce some triggers when the call is successful. For example, I have a function to fetch user data in a common class

fun getUserData(userId: Int) {
    userDataApi(userId)              
        .doOnSuccess { fetchAllImages() }
        .doOnError { Log.e(it) }
}

As you can see, there is no subscription yet. And the one who wants to use the above function can call it later on.

getUserData
    .subscribeOn(Schedulers.io())
    .observeOn(AndroidSchedulers.mainThread())
    .subscribe()

And if getUserData succeeds, it will always call fetchAllImages().

Bach Vu
  • 2,298
  • 1
  • 15
  • 19
  • Is there any case to use those method together ? And which one will be called first ? – Bulma Mar 15 '19 at 03:28
  • I have not yet found any difference between 2 of them, it is kind of based on your preference when you use them together – Bach Vu Mar 15 '19 at 03:46