RxJava Maybe: Any neat way to handle Empty case?

Mangat Rai Modi picture Mangat Rai Modi · Jun 6, 2018 · Viewed 8.8k times · Source

I am stuck at this problem, which should be fairly simple. I need subscriber to execute a code block when the Maybe has completed as an Empty Maybe. I found that

  1. we can pass default Maybe value or use switchIfEmpty but I feel both are hacky.
  2. Also there is a subscribe function which takes onComplete function (along with handlers for other two events), but onComplete does not take any argument which can be used to find if maybe was completed empty.
  3. Another way could be Maybe.isEmpty.blockingGet(), but it is dirty too.

I have tried following (Kotlin Syntax):-

fun <T> Maybe<T>.subscribeWithEmptyHandler(onSuccess: (T) -> Unit, onError: (Throwable) -> Unit, onEmpty: () -> Unit) {
    this.isEmpty.subscribe({ if (it) onEmpty() }, { onError(it) })
    this.subscribe({ onSuccess(it) }, { onError(it) })
}

But as expected it is running subscription twice, tested here:-

Maybe.create<Int> {
    println("subscribing")
    //Remove line below to create Empty Maybe
    it.onSuccess(5)
    it.onComplete()
}
    .subscribeWithEmptyHandler({println("success")},{println("error")},{println("empty")})

Could somebody please suggest neater way to solve this?

Answer

Dave Moten picture Dave Moten · Jun 7, 2018

Use Maybe.doOnEvent (java example):

Maybe
 .empty()
 .doOnEvent((value, error)-> {
    if (value==null && error == null) {
      System.out.println("empty!");
    }})
 .subscribe();