O10
O10

Reputation: 35

RxJava startsWith operator ignored when combined with observeOn

I have a simple stream like that:

Observable.error<Int>(Exception()).startWith(1).subscribe {
        println("Item is $it")
    }

Everything is working like expected. First onNext is called with integer 1 and then exception is thrown, however when I change the stream by adding observeOn like that:

Observable.error<Int>(Exception()).startWith(1).observeOn(AndroidSchedulers.mainThread()).subscribe {
        println("Item is $it")
    }

onNext is never called. Only the exception is thrown. What am I missing here?

Upvotes: 2

Views: 1078

Answers (1)

Sandip Fichadiya
Sandip Fichadiya

Reputation: 3480

From the observeOn document

Note that onError notifications will cut ahead of onNext notifications on the emission thread if Scheduler is truly asynchronous.

That means when you apply it, the onError is emitted first & hence the onNext is not called as the streams has ended due to onError.

You can do the following in order to receive the onNext first

observeOn(AndroidSchedulers.mainThread(), true)

This tells the Observable to delay the error till the onNext of startWith is passed

Upvotes: 5

Related Questions