개발 일기

Transformations LiveData 본문

Client/안드로이드

Transformations LiveData

이건욱

프로젝트를 진행하면서 MVVM을 사용을 할때 LiveData를 많이 사용을 합니다.

주로 Observable을 위해 사용하지만 더 많은 기능을 제공을 하기 때문에 알아보는 시간을 가지겠습니다.

 

Transformations :)

공식 문서에 소개 되어 있는 내용으로는 두가지 기능이 있습니다.

 

map :)

 LiveData userLiveData = ...;
 LiveData userName = Transformations.map(userLiveData, user -> {
      return user.firstName + " " + user.lastName
 });

저희가 알고 있는 컬렉션에서 제공하는 map과 비슷합니다.

 

첫번째 인자로 LiveDataSource를 받습니다.

두번째 인자로 함수를 받습니다.

따라서 해당 내용을 변환 시킨뒤 LiveData로 Return 합니다.

 

결론 :)

userLiveData가 값이 변경시 userName도 같이 값이 갱신이 됩니다. (MediatorLiveData 을 통해서 Merge)

 

switchMap :)

 MutableLiveData userIdLiveData = ...;
 LiveData userLiveData = Transformations.switchMap(userIdLiveData, id ->
     repository.getUserById(id));

 void setUserId(String userId) {
      this.userIdLiveData.setValue(userId);
 }

map 에서는 값을 변경을 했다면 이것은 LiveData를 Return을 해야 합니다!.

'Client > 안드로이드' 카테고리의 다른 글

Dialog Fragment ?  (0) 2020.04.20
앱 대기 버킷 ?  (0) 2020.04.06
다중 창 지원  (0) 2020.04.03
coroutine ktx  (0) 2020.03.30
Fragment recyclerView 관련 메모리 이슈  (0) 2020.03.27
Comments