问题
I am new in MVVM and Android Architecture component. so I have repository like this
object RestaurantRepository {
val restaurants : LiveData<ArrayList<Restaurant>> = RestaurantClient.restaurants
private var count : LiveData<Int> = Transformations.map(restaurants) {
Log.d("debugLog","map")
it.size
}
fun searchRestaurants(query: String, latitude:Double, longitude: Double) {
mQuery = query
RestaurantClient.searchRestaurants(
query = query,
latitude = latitude,
longitude = longitude,
start = 0
)
}
}
and I have client that getting data using Retrofit
object RestaurantClient {
val restaurants = MutableLiveData<ArrayList<Restaurant>>()
private val restaurantService = RetrofitServiceGenerator.getInstance(RestaurantAPI::class.java)
fun searchRestaurants(query: String, latitude:Double, longitude: Double, start: Int) {
val call = restaurantService.searchRestaurants(
radius = 2000,
query = query,
latitude = latitude,
longitude = longitude,
start = start,
count = NUMBER_OF_DOCUMENT_PER_PAGE
)
call.enqueue(object: Callback<RestaurantListBaseResponse> {
override fun onFailure(call: Call<RestaurantListBaseResponse>, t: Throwable) {
// if there is an error while sending data to server or while parsing the data
}
override fun onResponse(call: Call<RestaurantListBaseResponse>, response: Response<RestaurantListBaseResponse>) {
if (response.isSuccessful) {
val listOfRestaurants = response.body()!!.restaurants
val restos = ArrayList<Restaurant>()
for (i in listOfRestaurants ) {
restos.add(i.restaurant)
}
restaurants.postValue(restos)
}
})
}
I believe, I get the data from server and post it through restaurants
MutableLiveData in my RestaurantClient
. so I assume because there is a change in Livedata, then it will trigger the Transformations.map , but that log in count
never appear in my Logcat.
this count is private for only in RestaurantRepository
, this is just for a test because I am still learning about livedata
回答1:
According to docs
The transformations aren't calculated unless an observer is observing the returned LiveData object.
So, you need to subscribe to count
LiveData to make Transformations work.
来源:https://stackoverflow.com/questions/60628371/why-my-map-livedata-is-not-called-even-though-i-have-change-the-value