I am trying to use my search function with Paging 3. I checked my addQuery() function and my _repoQuery value is not null there when I do a search. But when I try to pass the value to the Pager {}, it is always null. I know that because it always brings up a list of books corresponding to the default value ("flowers"). Does anyone know how I can pass my _repoQuery value to the Pager {} when I do a search?
class MainViewModel () : ViewModel() {
// Queries
private val _repoQuery = MutableLiveData<String?>()
private val _filter = MutableLiveData<String?>()
val reusableQuery = MutableLiveData<String?>()
private val repo = Repo
fun addFilter(filter: String?) {
_filter.value = filter
}
fun addQuery(query: String) {
_repoQuery.value = query // Here _repoQuery.value exists
reusableQuery.value = _repoQuery.value
}
val books: Flow<PagingData<Volume>> = Pager(PagingConfig(pageSize = 40)) {
BookListSource(repo, bookFilter = _filter.value, query = _repoQuery.value?:"flowers")
}.flow.cachedIn(viewModelScope) // Here _repoQuery.value is null
}
Solution
This is what worked in the end:
val repoQuery = _repoQuery.switchMap {
liveData {
emit(Pager(PagingConfig(pageSize = 40)) {
BookListSource(repo, bookFilter = _filter.value, query = _repoQuery.value)
}.flow.cachedIn(viewModelScope))
}
}
My understanding is that the liveData is emitting fresh results as they arrive...