An elegant way to decide and manage the order of items in RecyclerView

Eric Lu
3 min readApr 23, 2017

--

Given a RecyclerView with multiple item data, each item’s data comes from different networking API results. All networking tasks are started simultaneously and their finishing orders are unpredictable.

4 item types in RecyclerView

For instance, if there are 4 types of item in RecyclerView, say, TYPE_1, …, TYPE_4. All of them are from different API results.

All APIs are started at the same time. For displaying the UI as quickly as possible, we show the result of each API when it is finished.

How to decide the order to insert?

A straightforward implementation is to create an array maintaining the item type of each item in the list. When an API is returned, we use methods like ArrayList#indexOf to find the appropriate position to insert. When the TYPE_2 result returns, a way to find the position to insert is as follows:

A complicated and error-prone way to decide position

It’s too complicated and annoying to handle all the situations that some results are not ready yet. If we have more item types in RecyclerView, things will get worse and worse.

Any better solutions?

Our goal is to eliminate all of the case-by-case statements, uses a general solution to handle all unpredictable orders instead. An idea is that we can assign an order constant to each item. If an API is completed, we will know the order value of the API result. Next, by comparing the order with all existing items’ order, we can get the order which should be insert into.

The order value of all items are showed as follows:

A code snippet demonstrating the idea:

If the TYPE_1 API (the top banner) is finished, we can use the following way to find the right position to insert:

Note that the TYPE_1 is just for demonstrating, it can be replaced with any item type. In a real case, I usually create a list for storing all descriptive information of an item, like: order, item type and data model, etc.

Why not using the same constants of item types as an item order?

Sometimes there are items which have the same item type but display in different positions. For example, we need to show a ViewPager item in the first and the third position of the list.

Conclusion

We always want to make our apps response as quickly as possible, but don’t mess up our codes. Using this elegant way, you can get rid of all case-by-case statements in your getItemViewType method and the method to find the correct position to insert.

--

--