Android14
Android14

Reputation: 1125

Not able to handle error while using Flowable in Rxjava

Flowable.just(getSize())
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .onExceptionResumeNext { Flowable.just(10) }
            .onErrorResumeNext(Flowable.just(10))
            .doOnError { throwable -> Logger.log("caught in doOnError") }
            .subscribe({ size -> showSizeOnUi(size) },
                    { throwable -> Logger.log("caught in onError") })

getSize() function will throw NullPointer Exception.

 private fun getSize(): Int {
    val path: String? = null
    return path!!.length  // attempts to call length on null string (path)
}

As far as i know, if getSize() throws any exception then controll should be given to the onExceptionResumeNext, which will then return '10' and this value should go to the onNext() "{ size -> showSizeOnUi(size) }". But in this case, app just crashes. Can i prevent this crash through any fallback mechanism ?

Thank you.

Upvotes: 2

Views: 3538

Answers (2)

neworld
neworld

Reputation: 7793

The expression Flowable.just(getSize()) will immediately throws NPE as @bob-dalgleish explains. But you could defer creation of Flowable:

    Flowable.defer { Flowable.just(getSize()) }
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .onExceptionResumeNext { Flowable.just(10) }
        .onErrorResumeNext(Flowable.just(10))
        .doOnError { throwable -> Logger.log("caught in doOnError") }
        .subscribe({ size -> showSizeOnUi(size) },
                { throwable -> Logger.log("caught in onError") })

Now Flowable.just(getSize()) will be called on subscribe() and RxJava is able to catch the exception.

Upvotes: 3

Bob Dalgleish
Bob Dalgleish

Reputation: 8227

The expression Flowable.just(getSize()) will immediately throw the NullPointerException and there is no opportunity for RxJava to catch it.

You need to surround the whole statement with a try {...} catch (...) {...} block.

Upvotes: 2

Related Questions