Android Jetpack Architecture/LiveData
LiveData( MediatorLiveData )
hik14
2020. 8. 18. 14:44
- MediatorLiveData는 LiveData의 서브클래스 이다.
- 클래스를 사용하여 여러 LiveData 소스를 병합가능하다.
- MediatorLiveData 객체의 관찰자는 원본 LiveData 소스 객체가 변경될 때마다 호출됩니다.

- 로컬 데이터베이스나 네트워크에서 업데이트할 수 있는 LiveData 객체가 UI에 있다면 다음 소스를 MediatorLiveData 객체에 추가하면 된다.
- 데이터베이스에 저장된 데이터와 연결된 LiveData 객체
- 네트워크에서 액세스하는 데이터와 연결된 LiveData 객체
- 소스에서 업데이트를 받기 위해 MediatorLiveData 객체만 관찰하면 된다.
예시) 단순히 2개의 라이브데이터를 MediatorLiveData 연결하면 2개중 1개가 변하면 MediatorLiveData가 트리거된다.
public class UserViewModel extends AndroidViewModel {
private static final String TAG = "UserViewModel";
MutableLiveData<User> localUser = new MutableLiveData<>();
MutableLiveData<User> remoteUser = new MutableLiveData<>();
MediatorLiveData userMediatorLiveData = new MediatorLiveData<>();
public UserViewModel(@NonNull Application application) {
super(application);
userMediatorLiveData.addSource(localUser, v -> userMediatorLiveData.setValue(v));
userMediatorLiveData.addSource(remoteUser, v -> userMediatorLiveData.setValue(v));
}
public MediatorLiveData<User> getUserMediatorLiveData() {
return userMediatorLiveData;
}
public void upDateLocalUser(){
Log.d(TAG, "upDateLocalUser: call");
localUser.setValue(new User("localUser", "1"));
}
public void upDateRemoteUser(){
Log.d(TAG, "upDateRemoteUser: call");
remoteUser.setValue(new User("remoteUser", "2"));
}
}
자세한 사항은 구글 공식 개발 블로그를 참조 하며 공부하였다.