I am using Paging library to get data from a webservice and display it in a recyclerview. However, I am not able to figure out a way to load initial data when the DataSource is loaded initially I am doing something similar to this tutorial.
override fun loadInitial(params: LoadInitialParams<String>, callback: LoadInitialCallback<String, RedditPost>) {}
I want to pass User.name, User.age etc to be passed from the ViewModel. How do you call this function?
You weren't that specific about what you're trying to pass in, so I'll try to cover both scenarios briefly:
The PagedList.Builder or any of its variants (LiveData, Rx, etc.), have an initialKey
argument you can pass in on instantiation, which is passed to DataSource
as the key in LoadParams
. This needs to match the Key
type of your DataSource
(Int
for PositionalDataSource
, etc).
You want to pass any dependencies via your DataSource
's constructor, passing it through DataSource.Factory during .create()
.
Edit: Generally if you trying to send events from the UI upstream and react on this, you'll want to do a .switchMap
. You didn't mention what architecture or post any code, but assuming you are using LiveData
, it may look something like:
ViewModel.kt
val queryFlow = MutableLiveData<String>("initialQuery")
val pagingDataFlow = queryFlow
.switchMap { query ->
LivePagedListBuilder(
dataSourceFactory = MyDataSourceFactory(query),
config = ...
)
...
.build()
}
.cachedIn(viewModelScope)
This allows you to start / cancel a new stream on each new query and pass the query into your DataSource.Factory
.