Rxjava: [2.x] how to throw exception to method

Created on 14 Feb 2017  路  2Comments  路  Source: ReactiveX/RxJava

how can RxJava v2 throw an exception to be handled imperatively? Is it possible?

    @Throws(Throwable::class)
    override fun onRun() {
              //synchronous stream....
                .subscribe(
                        {},
                        { throw it } //I need this exception to be thrown by the wrapping `onRun` method
                )
    }

In RxJava1 I could do the following:

    @Throws(Throwable::class)
    override fun onRun() {
              Observable.just("n/a")
                .map {
                    throw RuntimeException()
                }
                .subscribe(
                        {},
                        { throw it } //onRun() would catch the OnErrNotImplementedException, which I could unwrap
                ) 
     }

relevant documentation: https://github.com/ReactiveX/RxJava/wiki/What's-different-in-2.0#error-handling

Obviously this is messy and not reactive - but it's a limitation of a third party library I'm using.

2.x Question

Most helpful comment

You can't throw upwards with subscribe(). You can, however, store the exception in a field or on the heap and once subscribe returns, read it:

   var error = Throwable[1]
   Observable.just("n/a")
              .map {
                    throw RuntimeException()
              }
              .subscribe(
                        {},
                        { error[0] = it }
              ) 
    assertNonNull(error[0])

All 2 comments

You can't throw upwards with subscribe(). You can, however, store the exception in a field or on the heap and once subscribe returns, read it:

   var error = Throwable[1]
   Observable.just("n/a")
              .map {
                    throw RuntimeException()
              }
              .subscribe(
                        {},
                        { error[0] = it }
              ) 
    assertNonNull(error[0])

That's what I'm gonna do, thanks!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

hoc081098 picture hoc081098  路  3Comments

philleonard picture philleonard  路  3Comments

dlew picture dlew  路  4Comments

perlow picture perlow  路  3Comments

midnight-wonderer picture midnight-wonderer  路  3Comments