Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RxJava Maybe: Any neat way to handle Empty case?

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?

like image 285
Mangat Rai Modi Avatar asked Jun 06 '18 15:06

Mangat Rai Modi


1 Answers

Use Maybe.doOnEvent (java example):

Maybe
 .empty()
 .doOnEvent((value, error)-> {
    if (value==null && error == null) {
      System.out.println("empty!");
    }})
 .subscribe();
like image 200
Dave Moten Avatar answered Nov 11 '22 16:11

Dave Moten