2017-11-30 17 views
2

UI의 값은 두 개의 LiveData 개체에 따라 다릅니다. subtotal = sum of all items pricetotal = subtotal + shipment price이 필요한 가게를 상상해보십시오. (그것은 단지 itemsLiveData에 따라 달라로) 우리는 소계 LiveData 개체에 대해 다음과 같은 작업을 수행 할 수 Transformations 사용 :여러 인수가있는 LiveData Transformations.map()

val itemsLiveData: LiveData<List<Items>> = ... 
val subtotalLiveData = Transformations.map(itemsLiveData) { 
    items -> 
     getSubtotalPrice(items) 
} 

을 총의 경우가 좋은 것입니다 것은 같은 것을 할 수 있어야합니다 :

val shipPriceLiveData: LiveData<Int> = ... 
val totalLiveData = Transformations.map(itemsLiveData, shipPriceLiveData) { 
    items, price -> 
     getSubtotalPrice(items) + price 
} 

하지만 불행하게도지도 함수에 둘 이상의 인수를 넣을 수 없으므로 불가능합니다. 누구든지 이것을 성취 할 수있는 좋은 방법을 알고 있습니까?

답변

3

결국 MediatorLiveData를 사용하여 동일한 목표를 달성했습니다.

fun mapBasketTotal(source1: LiveData<List<Item>>, source2: LiveData<ShipPrice>): LiveData<String> { 
    val result = MediatorLiveData<String>() 
    uiThread { 
     var subtotal: Int = 0 
     var shipPrice: Int = 0 
     fun sumAndFormat(){ result.value = format(subtotal + shipPrice)} 
     result.addSource(source1, { items -> 
      if (items != null) { 
       subtotal = getSubtotalPrice(items) 
       sumAndFormat() 
      } 
     }) 
     result.addSource(source2, { price -> 
      if (price != null) { 
       shipPrice = price 
       sumAndFormat() 
      } 
     }) 
    } 
    return result 
} 
관련 문제