0

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!

1 Answers1

1

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.

ConstOrVar
  • 2,025
  • 1
  • 11
  • 14
  • So that means that in the first case the app will crash if the subscriber is disposed (if i'm using the default global error handler) and in the second it won't ? – Yuri Machioni Nov 15 '18 at 12:11
  • I suppose, yes. – ConstOrVar Nov 15 '18 at 13:07
  • RxJava 2.1.1 introduced an experimental tryOnError(t: Throwable) method on SingleEmitter. It's documentation says: "Attempts to emit the specified {@code Throwable} error if the downstream * hasn't cancelled the sequence or is otherwise terminated, returning false * if the emission is not allowed to happen due to lifecycle restrictions. *

    * Unlike {@link #onError(Throwable)}, the {@code RxJavaPlugins.onError} is not called * if the error could not be delivered." So I don't know how this fits what you said.

    – Yuri Machioni Nov 19 '18 at 15:46
  • Seems to me that both behave the same except tryOnError(), but if thats the case, everything before it would crash if disposal happens before onError ? How could I safely ignore a network error if the user (for an example) navigates away before the error is returned then ? This is really confusing. – Yuri Machioni Nov 19 '18 at 15:51