I'm using a PagingData inside a ViwModel with a Flow object. It's working correctly, but my problems is that, a certain point I need to reset/clear it to request new data.
I've tried different methods the objects has, but I haven't been able to do it. So, how can I achieve it?
Int he ViewModel
lateinit var items: Flow<PagingData<MyItem>>
private set
private fun initItemsFlow() {
items = repository.getItemsData().map { pagingData ->
pagingData.map { it }
}.cachedIn(viewModelScope)
}
This is the repository function:
fun getItemsData(): Flow<PagingData<MyItem>> = Pager(
PagingConfig(pageSize = 10, enablePlaceholders = false, prefetchDistance = 5)
) {
ItemsPagingSource()
}.flow
And finally, this is how I listen to it in the view
lifecycleScope.launchWhenStarted {
viewModel
.items
.collect {
iAdapter.submitData(it)
}
}
Thanks!
I don't know if it's the best solution, but I ended up creating a new PagingData
flow when I need to "clear/reset" the list. I have opted for this solution since I didn't find any method to reset the request to the data source.
So, in the fragment:
fun onResetList() {
viewModel.onResetList()
lifecycleScope.launch {
viewModel
.items
.collect {
itemsAdapter.submitData(it)
}
}
}
And, in the ViewModel I just recreate the flow object:
fun onResetList() {
items = repository.getItemsData().map { pagingData ->
pagingData.map { it }
}.cachedIn(viewModelScope)
}