Note
Note

Reputation: 183

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

Upvotes: 3

Views: 375

Answers (2)

DevWM
DevWM

Reputation: 114

  • Observable.just(1,2,3,4,5,6) -> The Just operator converts an items into an Observable that emits these items.
  • subscribeOn() -> operator tells the source Observable which thread to emit and push items on all the way down to Observer
  • observeOn() -> it will switch and pass emissions using that Scheduler for the remaining (downstream) operations
  • subscribe() -> operator returns Disposable object. You should assign this object to variable or to CompositeDisposable object. All disposables should be dispose (using dispose() method) while your Activity or Fragment ends life to avoid memory leak.

More you can find here: https://proandroiddev.com/understanding-rxjava-subscribeon-and-observeon-744b0c6a41ea

http://reactivex.io/documentation/operators.html#creating

You can also check Kotlin Coroutines as an alternative to RxJava

Upvotes: -1

mightyWOZ
mightyWOZ

Reputation: 8325

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

Upvotes: 2

Related Questions