0

I'm using the PagedList architectural components using a custom Paged datasource and I am having trouble returning results to the observe method.

below doesn't work:

fragment onviewcreated method

 override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
  viewModel?.searchDetails?.observe(viewLifecycleOwner, {
                populateSearchResults(it)
            }) 
}

viewmodel code where I update livedata from LivePagedListBuilder upon a user click event(not in viewmodel's init(){} method)

fun onProcessSearch(vararg searchValue: Array<String?>?) {
        val pagedListConfig = PagedList.Config.Builder()
                .setEnablePlaceholders(true)
                .setPageSize(PageSize).build()

        searchDetails = LivePagedListBuilder(PageKeyedSearchDataFactory(viewModelScope, searchValue[0]), pagedListConfig).build()
    }

below works,

just moving the observe part after calling the above view model function works, Fragment code:

 override fun onClick(view: View) {
viewModel?.onProcessSearch(searchValue)

if (view.id == R.id.match_patient_search_button) {
  patientDetailsViewModel?.patientSearchAddedDetails?.observe(viewLifecycleOwner, {
                populateSearchResults(it)
                GlobalHelper.hideKeyBoard(view)
            })
  }
}

Could anyone help why the above works, because as per doc we should observer livedata on onViewCreated method.

PrashanthR
  • 63
  • 6
  • Are you sure `viewModel?.searchDetails` is non-null when you expect to observe it? Usually, you'd want to use a `MutableLiveData` to pass the search term to your `ViewModel` and `.switchMap` that into the right `LiveData` so you can have a single flattened stream to observe, rather than need to re-create and re-observe a new stream every time you call onProcessSearch. Also is there any reason you're using paging2 over paging3? The entire PagedList API is deprecated in favor of PagingData now. – dlam Sep 19 '21 at 14:46
  • thanks for the suggestions making it a MutableLiveData and converting using map will fix it. And yes we are moving to Paging 3 soon. – PrashanthR Sep 21 '21 at 13:43

0 Answers0