android / architecture-components-samples

Samples for Android Architecture Components.
https://d.android.com/arch
Apache License 2.0
23.4k stars 8.29k forks source link

How to pass multiple parameters to the server when using paging and flow components #1022

Open smileusers opened 2 years ago

smileusers commented 2 years ago

The requirements are as follows: when obtaining the product list, you need to pass multiple parameters, for example, a query parameter and an order sorting parameter, but you don't know how to change them based on the pagingwithnetworksample project. The code is as follows:

ProductViewModel.kt

private val query = MutableLiveData<String>()
private val order = MutableLiveData<Int>(0)

fun setQuery(data: String?) {
    clearListChannel.trySend(Unit)

    query.value = data
}

fun setOrder(data: Int) {
    clearListChannel.trySend(Unit)

    order.value = data
}

init {
    query.value = null
}

val products = flowOf(
    clearListChannel.receiveAsFlow().map { PagingData.empty<Product>() },

  //Here is how to listen to the query and order fields and call the repository. Products method to query data as long as one field changes,Now just listen to the query field
    query.asFlow()
    .flatMapLatest {
        repository.products(order=0, query=it,pageSize = 10)
    }
    .cachedIn(viewModelScope)
).flattenMerge(2)

Because I'm not familiar with kotlin, flow and livedata, I don't know how to implement this function. I'm sorry to ask my friends for help; At the same time, how can the above functions be implemented in Java using the flowable implementation of rxjava