Android

[Android] AAC-LiveData의 setValue와 postValue

메징징 2021. 4. 23. 10:22
반응형

 

워크 스레드로 카운팅을 하는 앱에서 LiveData를 setValue()로 제대로 갱신되지 않는 상황이 발생했고,

postValue()로 변경하면서 해결했다.

그래서 까먹지 않기 위해 setValue와 postValue에 대한 정리를 하려고 한다 :)

 

setValue()

레퍼런스 문서를 보면 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. If you need set a value from a background thread, you can use postValue(Object)

정리된 그대로 setValue() 메서드는 메인스레드에서만 호출 가능하다.

setValue 메서드의 구현을 살펴보면

 @MainThread
 protected void setValue(T value) {
     assertMainThread("setValue");
     mVersion++;
     mData = value;
     dispatchingValue(null);
 }

assertMainThread를 통해 MainThread인지 판별하고, 아닐 경우 IllegalStateException을 던진다.

메인 스레드인 경우 즉시 값을 갱신한다.

 

postValue()

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.

postValue는 백그라운드 스레드에서 메인스레드의 루퍼에 Task를 전달하고, 메인스레드에서 이를 처리하는 방식으로 동작한다. 

protected void postValue(T value) {
    boolean postTask;
    synchronized (mDataLock) {
        postTask = mPendingData == NOT_SET;
        mPendingData = value;
    }
    if (!postTask) {
       return;
    }
    ArchTaskExecutor.getInstance().postToMainThread(mPostValueRunnable);
}

메인스레드로 전달하는 Task인 mPostValueRunnable에서 setValue를 호출한다.

바로 값 설정되는 것이 아니라, 메인스레드로 전달해서 처리되기까지 시간이 걸리기 때문에

postValue() 호출 후 바로 getValue()호출 시 설정 전 값을 읽어올 수도 있다

 

 

 

[참고] Android Reference Document - MutableLiveData

[참고] 쾌락 코딩 - AAC LiveData setValue() vs postValue()