Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confusion in Rx Java Android

Im new to rx and have some lines of code that confuse me:

Observable.just(1,2,3,4,5,6)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe { value ->
            Log.i("TEST", "$value")
        }
        .dispose()

it will not log the result but when i comment out subscribeOn () and observeOn() or dispose() then it works perfectly, like this:

Observable.just(1,2,3,4,5,6)
        .subscribe { value ->
            Log.i("TEST", "$value")
        }
        .dispose()

or

Observable.just(1,2,3,4,5,6)
        .subscribeOn(Schedulers.io())
        .observeOn(AndroidSchedulers.mainThread())
        .subscribe { value ->
            Log.i("TEST", "$value")
        }

Can someone explain what happen inside this chain

like image 732
Note Avatar asked Mar 22 '26 04:03

Note


1 Answers

When you write .subscribeOn(Schedulers.io()) this essentially means that Observable will operate on io thread, which will require a thread switch causing some delay. by the time it happens you have already called the dispose() method which disposes the Observable hence you don't receive any output.

On the other hand if you remove

.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())

This means Observable will operate on the calling thread so no thread switch is required, hence you receive complete output before dispose() method call can be executed.

If you only remove dispose() then nothing is stopping the Observable from emitting its contents even though its executing on io

like image 179
mightyWOZ Avatar answered Mar 23 '26 18:03

mightyWOZ