본문 바로가기
📱 Android

[Android] Livedata setValue, postvalue

by 콩드로이드 2023. 6. 23.

Livedata를 쓰면서 setValue, postValue의 차이점을 명확히 모르고 있었다 

둘 다 값을 적용하지만 무슨 차이가 있을까?


 

setValue

void setValue (T value)

 

메인쓰레드에서 호출되는 함수, 메인쓰레드에서 값을 바로 변경한다

공식문서에 보면, setValue에 아래와 같이 설명되어있다 

If you need set a value from a background thread, you can use postValue(Object)

setValue는 메인쓰레드에서 호출되기 때문에, 백그라운드에서 값을 설정하려면 postValue를 사용해야한다 

 

postValue

백그라운드에서 값을 설정하려면 postValue를 사용한다

안드로이드 스튜디오에서 postValue를 눌러보면 아래와같은 설명이 나온다

Posts a task to a main thread to set the given value. So if you have a following code executed in the main thread:
       liveData.postValue("a");
       liveData.setValue("b");
       
The value "b" would be set at first and later the main thread would override it with the value "a".
If you called this method multiple times before a main thread executed a posted task, only the last value would be dispatched.

처음엔 b가 설정되고, 나중에 메인스레드가 a로 override 시킨다