2

In the following piece of code:

    viewModelScope.launch {
  
        isLoading.postValue(true) 
            
        .....
   }

we are in main thread, because viewModelScope.launch is running on main thread by default, the same as viewModelScope.launch(dispatchers.main)

In main thread, does it make sense to use postValue? i mean, shouldn't it be as: isLoading.value = true ?

i have found plenty of this code chunk on internet, is it right or wrong??

sok sok
  • 215
  • 4
  • 9

2 Answers2

3

According to the documentation:

Based on the documentation:

setValue():

Sets the value. If there are active observers, the value will be dispatched to them. This method must be called from the main thread.

postValue():

Posts a task to a main thread to set the given value. If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.

So I would always use setValue when possible, in your case as you have noticed setValue is better because you can be sure it will always be on the Main Thread.

However postValue can also be called from the Main Thread, but will perform a tiny bit worse.

Merthan Erdem
  • 5,598
  • 2
  • 22
  • 29
1

Normally there is two ways to set a value of a liveData object :

  • setValue ==> main thread
  • postValue ==> others threads