With the help of new Paging3 library, it has made us easy to insert items/separators in a recyclerview as shown in the google android codelabs tutorial https://developer.android.com/codelabs/android-paging#11 but how to get the logic of inserting items at every n position say as at every position 10 in the recyclerview.
Sample code
fun searchRepo(queryString: String): Flow<PagingData<UiModel>> {
val lastResult = currentSearchResult
if (queryString == currentQueryValue && lastResult != null) {
return lastResult
}
currentQueryValue = queryString
val newResult: Flow<PagingData<UiModel>> = repository.getSearchResultStream(queryString)
.map { pagingData -> pagingData.map { UiModel.RepoItem(it) } }
.map {
it.insertSeparators<UiModel.RepoItem, UiModel> { before, after ->
if (after == null) {
// we're at the end of the list
return@insertSeparators null
}
if (before == null) {
// we're at the beginning of the list
return@insertSeparators UiModel.SeparatorItem("${after.roundedStarCount}0.000+ stars")
}
// check between 2 items
if (before.roundedStarCount > after.roundedStarCount) {
if (after.roundedStarCount >= 1) {
UiModel.SeparatorItem("${after.roundedStarCount}0.000+ stars")
} else {
UiModel.SeparatorItem("< 10.000+ stars")
}
} else {
// no separator
null
}
}
}
.cachedIn(viewModelScope)
currentSearchResult = newResult
return newResult
How to find the logic of adding an item on every 10th position in the above sample code
fun itemInsert(position: Int): Int {
return if (position % 10 == 0) //each 10 position is separator
SEPARATOR else COMMON
}