안녕하세요 여러분
오늘은 제가 프로젝트를 진행하던중 멘토님께서 물어보신 LiveData setValue 의 차이점에 대해 정리해볼려고 합니다.
일단 LiveData 가 무엇인가?
Google Android doc을 보시면 MVVM을 사용하는 예시 프로젝트가 많습니다.
그럴때 사용되는게 LiveData라는겁니다.
LiveData 은
이정도 인거 같습니다.
class MainActivityViewModel () : ViewModel() {
private var _liveData = MutableLiveData<String>()
val liveData get()= _liveData
fun liveDataExample() {
_liveData.postValue("Loading")
}
이 코드를 보신 멘토님은 딱 이질문을 남기셨습니다.
멘토님 : 음 코드 잘봤아요. 근데 여기서 왜 PostValue을 쓰셨나요 ?
Assist : ....?
멘토님: postValue 와 setValue의 차이점은 무엇인가요?
Assist : .....? ㅎㅎ...?
멘토님 : ^^ 다음주에 또 물어볼께요
그럼 setValue 와 PostValue 의 차이점을 알아보겠습니다.
한번 setValue 의 코드를 보겠습니다 .
@MainThread
protected void setValue(T value) {
assertMainThread("setValue");
mVersion++;
mData = value;
dispatchingValue(null);
}
메인 쓰레드로 움직이네요. setValue은 Main 쓰레드를 통해 값을 집어 넣는 함수 입니다.
그럼 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:
* <pre class="prettyprint">
* liveData.postValue("a");
* liveData.setValue("b");
* </pre>
* The value "b" would be set at first and later the main thread would override it with
* the value "a".
* <p>
* If you called this method multiple times before a main thread executed a posted task, only
* the last value would be dispatched.
*
* @param value The new value
*/
protected void postValue(T value) {
boolean postTask;
synchronized (mDataLock) {
postTask = mPendingData == NOT_SET;
mPendingData = value;
}
if (!postTask) {
return;
}
ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}
코드를 보면
공식 문서에 보면 postvalue 후 getValue 하면 postvalue 한 최신 값이 안나올수 있다 라는 구절이 나옵니다.
즉 postValue 은 비동기적으로 데이터를 집어 넣는다고 볼수 있습니다.
개발자는 자기가 판단해서 잘 써야 한다고 생각은 하지만 저였다면 이렇게 쓸거 같습니다.
setValue
postValue
이정도로 생각이 듭니다.
그럼 오늘도 읽어주셔서 감사합니다
-피드백와 비판은 언제나 환영입니다-
좋은 정보 감사합니다