0

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...

Code Poet
  • 6,222
  • 2
  • 29
  • 50

1 Answers1

1

Its null because your filter/query don't have any values when when the Pager is created. You need to remake the Pager when you change those values because the BookListSource you gave it is no longer valid. This isn't the prettiest thing in the world, but it should get you started.

//Make it once at the start to avoid lateinit 
var books : Flow<PagingData<Volume>> = Pager(PagingConfig(pageSize = 40)) {
          BookListSource(repo, bookFilter = _filter.value, query = _repoQuery.value?:"flowers")
     }.flow.cachedIn(viewModelScope) 

fun addFilter(filter: String?) {
    _filter.value = filter
    //filter changes so the BookListSource needs to be different
    books = Pager(PagingConfig(pageSize = 40)) {
         BookListSource(repo, bookFilter = _filter.value, query = _repoQuery.value?:"flowers")
    }.flow.cachedIn(viewModelScope) 
}

fun addQuery(query: String) {
    _repoQuery.value = query // Here _repoQuery.value exists
    reusableQuery.value = _repoQuery.value
    //query changes so the BookListSource needs to be different
    books = Pager(PagingConfig(pageSize = 40)) {
         BookListSource(repo, bookFilter = _filter.value, query = _repoQuery.value?:"flowers")
    }.flow.cachedIn(viewModelScope) 
}
avalerio
  • 2,072
  • 1
  • 12
  • 11