Search code examples
error-handlingkotlinobservablerx-java2rx-kotlin

In RxJava/RxKotlin, what are the differences between returning a Completable.error(Exception()) and throwing?


What are the differences in the following cases:

fun a(params: String) = Completable.fromAction {
        if (params.isEmpty()) {
            throw EmptyRequiredFieldException() 
        }
    }

VS

fun b(params: String) = if(params.isEmpty()) 
       Completable.error(EmptyRequiredFieldException()) 
else 
       Completable.complete()

Specifically in the context of android, if it matters (even though I don't think it does) Thanks!


Solution

  • According to documentation,

    If the Action throws an exception, the respective Throwable is delivered to the downstream via CompletableObserver.onError(Throwable), except when the downstream has disposed this Completable source. In this latter case, the Throwable is delivered to the global error handler via RxJavaPlugins.onError(Throwable) as an UndeliverableException.

    So both of two ways you described are similar (except when the downstream has disposed). Note, that first approach (with manually throwing exception) allow to modify behavior of Completable at runtime. And second one - statically defined as you return particular type of Completable and can't modify it.

    What to choose depends on your needs.