I’m using paging3 lib
class RepoResultPagingSource(
private val repository: Repository,
private val query: String
) : PagingSource<Int, RepoResult>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, RepoResult> {
try {
val nextPageNumber = params.key ?: 1
Log.d("TRACE", "Loading page number $nextPageNumber")
val repos = repository.getRepositories(query, nextPageNumber)
// form a page worth of RepoResult
val repoResults = repos.map { repo ->
val contributor = repository.getTopContributor(repo.owner.login, repo.name)
RepoResult(repo.owner.avatarUrl, repo.name, contributor.login?: "")
}
return LoadResult.Page(
data = repoResults,
prevKey = null,
nextKey = nextPageNumber + 1
)
} catch (e: Exception) {
Log.d("TRACE", "encountered ${e.message}")
return LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState<Int, RepoResult>): Int {
return 1
}
}
in my activity I collect like
lifecycleScope.launch {
repeatOnLifecycle(Lifecycle.State.STARTED) {
viewModel.pagingData.collect { pagingData ->
adapter.submitData(pagingData)
}
}
}
my adapter
class RepoResultAdapter : PagingDataAdapter<RepoResult,
RepoResultAdapter.RepoResultViewHolder>(DIFF_CALLBACK) {
companion object {
private val DIFF_CALLBACK = object : DiffUtil.ItemCallback<RepoResult>() {
override fun areItemsTheSame(oldItem: RepoResult, newItem: RepoResult):
Boolean {
return oldItem.name == newItem.name
}
override fun areContentsTheSame(oldItem: RepoResult, newItem: RepoResult):
Boolean {
return oldItem == newItem
}
}
}
inner class RepoResultViewHolder(view: View) :
RecyclerView.ViewHolder(view) {
private val repoTV = view.findViewById<TextView>(R.id.tv_repo_name)
private val contributorTV = view.findViewById<TextView>(R.id.tv_contributor)
private val repoIV = view.findViewById<ImageView>(R.id.iv_owner)
fun bind(repoResult: RepoResult) {
repoTV.text = repoResult.name
contributorTV.text = repoResult.topContributor
Glide.with(itemView)
.load(repoResult.avatarUrl)
.into(repoIV)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int):
RepoResultViewHolder {
val inflater = LayoutInflater.from(parent.context)
val binding = inflater.inflate(R.layout.item_repository, parent, false)
return RepoResultViewHolder(binding)
}
override fun onBindViewHolder(holder: RepoResultViewHolder, position: Int) {
getItem(position)?.let {
holder.bind(it)
}
}
}
it displays less than 2 pages of data even though the logs show that 4 pages are loaded before encountering a network exception. 2 questions
1.How do I resume loading pages after an exception
2.If my log in pagingsource says I’m on page 4 why do I see less than 2 pages of rows?