Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RecyclerView and background requests with large collection of items

I have a RecyclerView with a large collection bound to it, say 500+ items. When onBindViewHolder is called I make a async HTTP request to load some data.

But when I scroll really fast down the list, how do i cancel the requests for all items that are no longer in view? I am seeing 100's of requests start in the background because of how RecyclerView loads, i think onBindViewHolder is called for every item i scroll past?

I was thinking to kick off a request in onBindViewHolder that waits 500ms and if the item bound to it is still in view / still the same then starts the async request. Would this work? If so then how do i check if the item is in view still from within the Adapter ?

What's the correct way to solve this problem?

like image 775
lahsrah Avatar asked Jul 13 '16 01:07

lahsrah


People also ask

What are the three mandatory methods of a RecyclerView?

These required methods are as follows: onCreateViewHolder(ViewGroup parent, int viewType) onBindViewHolder(RecyclerView. ViewHolder holder, int position)

Which is better ListView or RecyclerView?

Simple answer: You should use RecyclerView in a situation where you want to show a lot of items, and the number of them is dynamic. ListView should only be used when the number of items is always the same and is limited to the screen size.

How many times onCreateViewHolder is called in RecyclerView?

By default it have 5. you can increase as per your need. Save this answer.


1 Answers

You can make a OnScrollListener for RecyclerView:

 public void onScrollStateChanged(AbsListView view, int scrollState) {
    if (scrollState == SCROLL_STATE_IDLE){
        int firstVisibleItem = view.getFirstVisiblePosition();
        int lastVisiblePosition = view.getLastVisiblePosition();

        //call request from firstVisibleItem to lastVisiblePosition 

    }
}
like image 66
mdtuyen Avatar answered Oct 13 '22 03:10

mdtuyen