PagedListAdapter

Added in 2.0.0
Deprecated in 3.0.0

RecyclerView.Adapter base class for presenting paged data from androidx.paging.PagedLists in a RecyclerView.

This class is a convenience wrapper around AsyncPagedListDiffer that implements common default behavior for item counting, and listening to PagedList update callbacks.

While using a LiveData is an easy way to provide data to the adapter, it isn't required - you can use submitList when new lists are available.

PagedListAdapter listens to PagedList loading callbacks as pages are loaded, and uses DiffUtil on a background thread to compute fine grained updates as new PagedLists are received.

Handles both the internal paging of the list as more data is loaded, and updates in the form of new PagedLists.

A complete usage pattern with Room would look like this:

@Dao
interface UserDao {
@Query("SELECT * FROM user ORDER BY lastName ASC")
public abstract DataSource.Factory<Integer, User> usersByLastName();
}

class MyViewModel extends ViewModel {
public final LiveData<PagedList<User>> usersList;
public MyViewModel(UserDao userDao) {
usersList = new LivePagedListBuilder&lt;>(
userDao.usersByLastName(), /* page size */20).build();
}
}

class MyActivity extends AppCompatActivity {
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
MyViewModel viewModel = new ViewModelProvider(this).get(MyViewModel.class);
RecyclerView recyclerView = findViewById(R.id.user_list);
UserAdapter&lt;User> adapter = new UserAdapter();
viewModel.usersList.observe(this, pagedList -> adapter.submitList(pagedList));
recyclerView.setAdapter(adapter);
}
}

class UserAdapter extends PagedListAdapter<User, UserViewHolder> {
public UserAdapter() {
super(DIFF_CALLBACK);
}
@Override
public void onBindViewHolder(UserViewHolder holder, int position) {
User user = getItem(position);
if (user != null) {
holder.bindTo(user);
} else {
// Null defines a placeholder item - PagedListAdapter will automatically invalidate
// this row when the actual object is loaded from the database
holder.clear();
}
}
public static final DiffUtil.ItemCallback&lt;User> DIFF_CALLBACK =
new DiffUtil.ItemCallback<User>() {
@Override
public boolean areItemsTheSame(@NonNull User oldUser, @NonNull User newUser) {
// User properties may have changed if reloaded from the DB, but ID is fixed
return oldUser.getId() == newUser.getId();
}
@Override
public boolean areContentsTheSame(@NonNull User oldUser, @NonNull User newUser) {
// NOTE: if you use equals, your object must properly override Object#equals()
// Incorrectly returning false here will result in too many animations.
return oldUser.equals(newUser);
}
}
}

Advanced users that wish for more control over adapter behavior, or to provide a specific base class should refer to AsyncPagedListDiffer, which provides the mapping from paging events to adapter-friendly callbacks.

Parameters
<T : Any>

Type of the PagedLists this Adapter will receive.

<VH : RecyclerView.ViewHolder>

A class that extends ViewHolder that will be used by the adapter.

Summary

Protected constructors

<T : Any, VH : RecyclerView.ViewHolder> PagedListAdapter(
    config: AsyncDifferConfig<T>
)
android
<T : Any, VH : RecyclerView.ViewHolder> PagedListAdapter(
    diffCallback: DiffUtil.ItemCallback<T>
)

Creates a PagedListAdapter with default threading and androidx.recyclerview.widget.ListUpdateCallback.

android

Public functions

open Unit

Add a LoadState listener to observe the loading state of the current PagedList.

android
open Int

Returns the total number of items in the data set held by the adapter.

android
open Unit
onCurrentListChanged(currentList: PagedList<T>?)

This function is deprecated. Use the two argument variant instead.

android
open Unit
onCurrentListChanged(
    previousList: PagedList<T>?,
    currentList: PagedList<T>?
)

Called when the current PagedList is updated.

android
open Unit

Remove a previously registered LoadState listener.

android
open Unit
submitList(pagedList: PagedList<T>?)

Set the new list to be displayed.

android
open Unit
submitList(pagedList: PagedList<T>?, commitCallback: Runnable?)

Set the new list to be displayed.

android
ConcatAdapter

Create a ConcatAdapter with the provided LoadStateAdapters displaying the LoadType.APPEND as a list item at the start of the presented list.

android
ConcatAdapter

Create a ConcatAdapter with the provided LoadStateAdapters displaying the LoadType.PREPEND as a list item at the end of the presented list.

android
ConcatAdapter
withLoadStateHeaderAndFooter(
    header: LoadStateAdapter<*>,
    footer: LoadStateAdapter<*>
)

Create a ConcatAdapter with the provided LoadStateAdapters displaying the LoadType.PREPEND and LoadType.APPENDs as list items at the start and end respectively.

android

Protected functions

open T?
getItem(position: Int)
android

Public properties

open PagedList<T>?

Returns the PagedList currently being displayed by the PagedListAdapter.

android

Inherited functions

From androidx.recyclerview.widget.RecyclerView.Adapter
Unit
bindViewHolder(holder: VH, position: Int)

This method internally calls onBindViewHolder to update the ViewHolder contents with the item at the given position and also sets up some private fields to be used by RecyclerView.

android
VH
createViewHolder(parent: ViewGroup, viewType: Int)

This method calls onCreateViewHolder to create a new ViewHolder and initializes some private fields to be used by RecyclerView.

android
open Int
findRelativeAdapterPositionIn(
    adapter: RecyclerView.Adapter<RecyclerView.ViewHolder>,
    viewHolder: RecyclerView.ViewHolder,
    localPosition: Int
)

Returns the position of the given ViewHolder in the given Adapter.

android
open Long
getItemId(position: Int)

Return the stable ID for the item at position.

android
open Int
getItemViewType(position: Int)

Return the view type of the item at position for the purposes of view recycling.

android
RecyclerView.Adapter.StateRestorationPolicy

Returns when this Adapter wants to restore the state.

android
Boolean

Returns true if one or more observers are attached to this adapter.

android
Boolean

Returns true if this adapter publishes a unique long value that can act as a key for the item at a given position in the data set.

android
Unit

Notify any registered observers that the data set has changed.

android
Unit

Notify any registered observers that the item at position has changed.

android
Unit
notifyItemChanged(position: Int, payload: Any?)

Notify any registered observers that the item at position has changed with an optional payload object.

android
Unit

Notify any registered observers that the item reflected at position has been newly inserted.

android
Unit
notifyItemMoved(fromPosition: Int, toPosition: Int)

Notify any registered observers that the item reflected at fromPosition has been moved to toPosition.

android
Unit
notifyItemRangeChanged(positionStart: Int, itemCount: Int)

Notify any registered observers that the itemCount items starting at position positionStart have changed.

android
Unit
notifyItemRangeChanged(positionStart: Int, itemCount: Int, payload: Any?)

Notify any registered observers that the itemCount items starting at position positionStart have changed.

android
Unit
notifyItemRangeInserted(positionStart: Int, itemCount: Int)

Notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted.

android
Unit
notifyItemRangeRemoved(positionStart: Int, itemCount: Int)

Notify any registered observers that the itemCount items previously located at positionStart have been removed from the data set.

android
Unit

Notify any registered observers that the item previously located at position has been removed from the data set.

android
open Unit

Called by RecyclerView when it starts observing this Adapter.

android
abstract Unit
onBindViewHolder(holder: VH, position: Int)

Called by RecyclerView to display the data at the specified position.

android
open Unit
onBindViewHolder(holder: VH, position: Int, payloads: MutableList<Any>)

Called by RecyclerView to display the data at the specified position.

android
abstract VH
onCreateViewHolder(parent: ViewGroup, viewType: Int)

Called when RecyclerView needs a new ViewHolder of the given type to represent an item.

android
open Unit

Called by RecyclerView when it stops observing this Adapter.

android
open Boolean

Called by the RecyclerView if a ViewHolder created by this Adapter cannot be recycled due to its transient state.

android
open Unit

Called when a view created by this adapter has been attached to a window.

android
open Unit

Called when a view created by this adapter has been detached from its window.

android
open Unit
onViewRecycled(holder: VH)

Called when a view created by this adapter has been recycled.

android
open Unit

Register a new observer to listen for data changes.

android
open Unit
setHasStableIds(hasStableIds: Boolean)

Indicates whether each item in the data set can be represented with a unique identifier of type java.lang.Long.

android
open Unit

Sets the state restoration strategy for the Adapter.

android
open Unit

Unregister an observer currently listening for data changes.

android

Protected constructors

PagedListAdapter

protected <T : Any, VH : RecyclerView.ViewHolder> PagedListAdapter(
    config: AsyncDifferConfig<T>
)

PagedListAdapter

protected <T : Any, VH : RecyclerView.ViewHolder> PagedListAdapter(
    diffCallback: DiffUtil.ItemCallback<T>
)

Creates a PagedListAdapter with default threading and androidx.recyclerview.widget.ListUpdateCallback.

Convenience for PagedListAdapter, which uses default threading behavior.

Parameters
diffCallback: DiffUtil.ItemCallback<T>

The DiffUtil.ItemCallback instance to compare items in the list.

Public functions

addLoadStateListener

open fun addLoadStateListener(listener: (LoadType, LoadState) -> Unit): Unit

Add a LoadState listener to observe the loading state of the current PagedList.

As new PagedLists are submitted and displayed, the listener will be notified to reflect current LoadType.REFRESH, LoadType.PREPEND, and LoadType.APPEND states.

Parameters
listener: (LoadType, LoadState) -> Unit

Listener to receive LoadState updates.

getItemCount

open fun getItemCount(): Int

Returns the total number of items in the data set held by the adapter.

Returns
Int

The total number of items in this adapter.

onCurrentListChanged

open fun onCurrentListChanged(currentList: PagedList<T>?): Unit

Called when the current PagedList is updated.

This may be dispatched as part of submitList if a background diff isn't needed (such as when the first list is passed, or the list is cleared). In either case, PagedListAdapter will simply call notifyItemRangeInserted/Removed(0, mPreviousSize).

This method will notbe called when the Adapter switches from presenting a PagedList to a snapshot version of the PagedList during a diff. This means you cannot observe each PagedList via this method.

Parameters
currentList: PagedList<T>?

new PagedList being displayed, may be null.

onCurrentListChanged

open fun onCurrentListChanged(
    previousList: PagedList<T>?,
    currentList: PagedList<T>?
): Unit

Called when the current PagedList is updated.

This may be dispatched as part of submitList if a background diff isn't needed (such as when the first list is passed, or the list is cleared). In either case, PagedListAdapter will simply call notifyItemRangeInserted/Removed(0, mPreviousSize).

This method will notbe called when the Adapter switches from presenting a PagedList to a snapshot version of the PagedList during a diff. This means you cannot observe each PagedList via this method.

Parameters
previousList: PagedList<T>?

PagedList that was previously displayed, may be null.

currentList: PagedList<T>?

new PagedList being displayed, may be null.

removeLoadStateListener

open fun removeLoadStateListener(listener: (LoadType, LoadState) -> Unit): Unit

Remove a previously registered LoadState listener.

Parameters
listener: (LoadType, LoadState) -> Unit

Previously registered listener.

submitList

open fun submitList(pagedList: PagedList<T>?): Unit

Set the new list to be displayed.

If a list is already being displayed, a diff will be computed on a background thread, which will dispatch Adapter.notifyItem events on the main thread.

Parameters
pagedList: PagedList<T>?

The new list to be displayed.

submitList

open fun submitList(pagedList: PagedList<T>?, commitCallback: Runnable?): Unit

Set the new list to be displayed.

If a list is already being displayed, a diff will be computed on a background thread, which will dispatch Adapter.notifyItem events on the main thread.

The commit callback can be used to know when the PagedList is committed, but note that it may not be executed. If PagedList B is submitted immediately after PagedList A, and is committed directly, the callback associated with PagedList A will not be run.

Parameters
pagedList: PagedList<T>?

The new list to be displayed.

commitCallback: Runnable?

Optional runnable that is executed when the PagedList is committed, if it is committed.

withLoadStateFooter

fun withLoadStateFooter(footer: LoadStateAdapter<*>): ConcatAdapter

Create a ConcatAdapter with the provided LoadStateAdapters displaying the LoadType.APPEND as a list item at the start of the presented list.

withLoadStateHeader

fun withLoadStateHeader(header: LoadStateAdapter<*>): ConcatAdapter

Create a ConcatAdapter with the provided LoadStateAdapters displaying the LoadType.PREPEND as a list item at the end of the presented list.

withLoadStateHeaderAndFooter

fun withLoadStateHeaderAndFooter(
    header: LoadStateAdapter<*>,
    footer: LoadStateAdapter<*>
): ConcatAdapter

Create a ConcatAdapter with the provided LoadStateAdapters displaying the LoadType.PREPEND and LoadType.APPENDs as list items at the start and end respectively.

Protected functions

getItem

protected open fun getItem(position: Int): T?

Public properties

currentList

open val currentListPagedList<T>?

Returns the PagedList currently being displayed by the PagedListAdapter.

This is not necessarily the most recent list passed to submitList, because a diff is computed asynchronously between the new list and the current list before updating the currentList value. May be null if no PagedList is being presented.

Returns
PagedList<T>?

The list currently being displayed.