I'm trying to make a recycler view that load more data as the user scroll down without deleting the previous cell. example:(Instagram, twitter...)
when I scroll down the new data is fetched in all the recycler-view cells the previous and the new cells.
so if I have 10cells, then I scroll down, it gets another new 10 however now all 20 are the same, and the first 10 are substituted.
The Main fragment
photosList.layoutManager = mLayoutManager
viewModel.refresh()
photosList.apply {
layoutManager = LinearLayoutManager(context)
adapter = photosAdapter
}
observeViewModel()
photosList.addOnScrollListener(object : RecyclerView.OnScrollListener() {
override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
if (dy > 0) { //check for scroll down
//visibleItemCount = mLayoutManager.childCount
var layoutManager = photosList.layoutManager as LinearLayoutManager
visibleItemCount =
layoutManager.findLastVisibleItemPosition() - layoutManager.findFirstVisibleItemPosition() + 1
totalItemCount = layoutManager.itemCount
pastVisibleItems = layoutManager.findFirstVisibleItemPosition()
if (loading) {
if (visibleItemCount + pastVisibleItems >= totalItemCount) {
loading = false
// Fetch new data
viewModel.fetchMorePhotos()
observeViewModelGetMore()
loading = true
}
}
}
}
})
The ViewModel
fun fetchMorePhotos() {
pageNumber += 1
fetchPhotos()
}
private fun fetchPhotos() {
loading.value = true
//loading2.value = true
disposable.add(
PhotosService.getPhotos(pageNumber)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribeWith(object : DisposableSingleObserver<List<PhotoData>>() {
override fun onSuccess(value: List<PhotoData>?) {
Photos.value = value!!
PhotoLoadError.value = false
loading.value = false
//loading2.value = false
}
override fun onError(e: Throwable?) {
PhotoLoadError.value = true
loading.value = false
//loading2.value = false
}
})
)
}
The Adapter
class PhotoListAdapter(
var photos: ArrayList<PhotoData>,
private var click_listener: OnPhotoItemClickListner
) :
RecyclerView.Adapter<PhotoListAdapter.PhotoViewHolder>() {
fun updatePhotos(newPhotos: List<PhotoData>) {
photos.clear()
photos.addAll(newPhotos)
notifyDataSetChanged()
}
fun getMorePhotos(newPhotos: List<PhotoData>) {
val position: Int = photos.size + 1
photos.addAll(newPhotos)
notifyItemChanged(position,newPhotos)
}
Infinite scrolling is a complicated topic that I wouldn't try to solve yourself. You'll want to use the Android Paging library:
https://proandroiddev.com/infinite-scrolling-with-android-paging-library-and-flow-api-e017f47517d6