I'm making a network call and I fetch from server 50 items which I display on the RecyclerView
. If user keeps scrolling I fetch 50 more (using a page_num = 2, 3, etc...) and it keeps going like that with 50 items every time.
So let's say that currently there are being displayed 150 items to the user . What I'm doing is :
// This call is inside my `Fragment` class
for (NotificationsServiceResponseNestedItem item: notificationsList){
if (!dataset.contains(item)) {
adapter.addItem(item);
}
}
// this call is inside my `Adapter` class
public void addItem(NotificationsServiceResponseNestedItem item) {
dataset.add(item);
notifyItemInserted(dataset.size() - 1);
}
If user scrolled so there are 150 items in my adapter that means the above loop executed 3 times. I also keep the dataset both in my Fragment
and in my Adapter
class ( but that's something not related with my question - I just pointed out so there are no any misconceptions )
Now if user stays in this screen I keep calling the server every X secs, so I keep getting the same 50 items ( loop does not runs at all since if condition is not true and everythings is OK ). Sometimes there are a couple of new items so let's say from the 50 items I get from server : 48 already exist and are being displayed in my RecyclerView and two of them are new - so I should add them to adapter and display them.
The problem is : notifyItemInserted(dataset.size() - 1);
cause instead of adding the items at the first two positions, it adds them to the two last positions! Which is obviously wrong.
I've been looking at it the last couple of hours, but can't find an easy fix for that. Any ideas ?