Is observeOn requried for livedata postvalue?

Is observe on part required in this case or posting value in livedata is itself enough for it to be processed correctly.

method()
  .subscribeOn(Schedulers.io())
  .observeOn(AndroidSchedulers.mainThread())
  .subscribe(
     { liveData.postValue(it) },
     { Timber.e(it) }
  )

Upvotes: 4

Views: 515

Answers (2)

arungiri_10
arungiri_10

Reputation: 988

observeOn() -> This method simply changes the thread of all operators further downstream (in the calls that come after).

observeOn() -> This only influences the thread that is used when the Observable is subscribed to and it will stay on it downstream

If the above case mentioned in question, if the calls after observeOn(AndroidSchedulers.mainThread()) needs to run on UI thread, basically liveData.postValue(it) does some changes on UI thread, then this line is needed.

If it's removed, the further calls will be run on thread spawned by subscribeOn() method.

Below link gives a nice explanation of subscribeOn() and observeOn() method: https://medium.com/upday-devs/rxjava-subscribeon-vs-observeon-9af518ded53a

Hope this helps.

Upvotes: 0

Ricardo Costeira
Ricardo Costeira

Reputation: 3331

observeOn will force all operations below it to run on a thread from the scheduler you pass as its parameter. In this case, you're forcing the subscription to work on the main thread. Read this for more information.

Livedata has two ways of updating its value: you either do livedata.setValue(newValue) (livedata.value = newValue in Kotlin) or livedata.postValue(newValue). The first option only works on the main thread. On the other hand, postValue is commonly used to set the value from a background thread (the background thread actually posts a task for the main thread to update the value).

Given all this, in this case, since you're using postValue, you don't need to force the subscription on the main thread. However, note that since postValue is not synchronous, calling it from the main thread does not guarantee immediate execution. For instance, in your subscriber, if you call a livedata.postValue(newValue) followed by livedata.setValue(anotherValue), setValue will execute first. In other words, your livedata's value will be set to anotherValue, and later overridden to newValue. If you want to keep the execution in the main thread, use setValue.

Upvotes: 6

Related Questions