Skip to content

Most visited

Recently visited

navigation

KeyedDataSource

public abstract class KeyedDataSource
extends DataSource<Key, Value>

java.lang.Object
   ↳ android.arch.paging.DataSource<Key, Value>
     ↳ android.arch.paging.KeyedDataSource<Key, Value>


Incremental data loader for paging keyed content, where loaded content uses previously loaded items as input to future loads.

Implement a DataSource using KeyedDataSource if you need to use data from item N-1 to load item N. This is common, for example, in sorted database queries where attributes of the item such just before the next query define how to execute it.

A compute usage pattern with Room SQL queries would look like this (though note, Room plans to provide generation of much of this code in the future):

 @Dao
 interface UserDao {
     @Query("SELECT * from user ORDER BY name DESC LIMIT :limit")
     public abstract List<User> userNameInitial(int limit);

     @Query("SELECT * from user WHERE name < :key ORDER BY name DESC LIMIT :limit")
     public abstract List<User> userNameLoadAfter(String key, int limit);

     @Query("SELECT * from user WHERE name > :key ORDER BY name ASC LIMIT :limit")
     public abstract List<User> userNameLoadBefore(String key, int limit);
 }

 public class KeyedUserQueryDataSource extends KeyedDataSource<String, User> {
     private MyDatabase mDb;
     private final UserDao mUserDao;
     @SuppressWarnings("FieldCanBeLocal")
     private final InvalidationTracker.Observer mObserver;

     public KeyedUserQueryDataSource(MyDatabase db) {
         mDb = db;
         mUserDao = db.getUserDao();
         mObserver = new InvalidationTracker.Observer("user") {
             @Override
             public void onInvalidated(@NonNull Set<String> tables) {
                 // the user table has been invalidated, invalidate the DataSource
                 invalidate();
             }
         };
         db.getInvalidationTracker().addWeakObserver(mObserver);
     }

     @Override
     public boolean isInvalid() {
         mDb.getInvalidationTracker().refreshVersionsSync();
         return super.isInvalid();
     }

     @Override
     public String getKey(@NonNull User item) {
         return item.getName();
     }

     @Override
     public List<User> loadInitial(int pageSize) {
         return mUserDao.userNameInitial(pageSize);
     }

     @Override
     public List<User> loadBefore(@NonNull String userName, int pageSize) {
         // Return items adjacent to 'userName' in reverse order
         // it's valid to return a different-sized list of items than pageSize, if it's easier
         return mUserDao.userNameLoadBefore(userName, pageSize);
     }

     @Override
     public List<User> loadAfter(@Nullable String userName, int pageSize) {
         // Return items adjacent to 'userName'
         // it's valid to return a different-sized list of items than pageSize, if it's easier
         return mUserDao.userNameLoadAfter(userName, pageSize);
     }
 }

Summary

Inherited fields

From class android.arch.paging.DataSource

Public constructors

KeyedDataSource()

Public methods

final int countItems()

Number of items that this DataSource can provide in total, or COUNT_UNDEFINED.

int countItemsAfter(Key key)

Return the number of items that occur after the item uniquely identified by key in the data set.

int countItemsBefore(Key key)

Return the number of items that occur before the item uniquely identified by key in the data set.

abstract Key getKey(Value item)

Return a key associated with the given item.

abstract List<Value> loadAfter(Key currentEndKey, int pageSize)

Load list data after the specified item.

abstract List<Value> loadBefore(Key currentBeginKey, int pageSize)

Load data before the currently loaded content, starting at the provided index, in reverse-display order.

abstract List<Value> loadInitial(int pageSize)

Inherited methods

From class android.arch.paging.DataSource
From class java.lang.Object

Public constructors

KeyedDataSource

KeyedDataSource ()

Public methods

countItems

int countItems ()

Number of items that this DataSource can provide in total, or COUNT_UNDEFINED.

Returns
int number of items that this DataSource can provide in total, or COUNT_UNDEFINED if difficult or undesired to compute.

countItemsAfter

int countItemsAfter (Key key)

Return the number of items that occur after the item uniquely identified by key in the data set.

For example, if you're loading items sorted by ID, then this would return the total number of items with ID greater than key.

If you return COUNT_UNDEFINED here, or from countItemsBefore(Key), your data source will not present placeholder null items in place of unloaded data.

Parameters
key Key: A unique identifier of an item in the data set.

Returns
int Number of items in the data set after the item identified by key, or COUNT_UNDEFINED.

See also:

countItemsBefore

int countItemsBefore (Key key)

Return the number of items that occur before the item uniquely identified by key in the data set.

For example, if you're loading items sorted by ID, then this would return the total number of items with ID less than key.

If you return COUNT_UNDEFINED here, or from countItemsAfter(Key), your data source will not present placeholder null items in place of unloaded data.

Parameters
key Key: A unique identifier of an item in the data set.

Returns
int Number of items in the data set before the item identified by key, or COUNT_UNDEFINED.

See also:

getKey

Key getKey (Value item)

Return a key associated with the given item.

If your KeyedDataSource is loading from a source that is sorted and loaded by a unique integer ID, you would return item.getID() here. This key can then be passed to loadBefore(Key, int) or loadAfter(Key, int) to load additional items adjacent to the item passed to this function.

If your key is more complex, such as when you're sorting by name, then resolving collisions with integer ID, you'll need to return both. In such a case you would use a wrapper class, such as Pair<String, Integer> or, in Kotlin, data class Key(val name: String, val id: Int)

Parameters
item Value: Item to get the key from.

Returns
Key Key associated with given item.

loadAfter

List<Value> loadAfter (Key currentEndKey, 
                int pageSize)

Load list data after the specified item.

It's valid to return a different list size than the page size, if it's easier for this data source. It is generally safer to increase the number loaded than reduce.

Parameters
currentEndKey Key: Load items after this key. May be null on initial load, to indicate load from beginning.

pageSize int: Suggested number of items to load.

Returns
List<Value> List of items, starting after the specified item. Null if the data source is no longer valid, and should not be queried again.

loadBefore

List<Value> loadBefore (Key currentBeginKey, 
                int pageSize)

Load data before the currently loaded content, starting at the provided index, in reverse-display order.

It's valid to return a different list size than the page size, if it's easier for this data source. It is generally safer to increase the number loaded than reduce.

Note: Items returned from loadBefore must be in reverse order from how they will be presented in the list. The first item in the return list will be prepended immediately before the current beginning of the list. This is so that the KeyedDataSource may return a different number of items from the requested pageSize by shortening or lengthening the return list as it desires.

Parameters
currentBeginKey Key: Load items before this key.

pageSize int: Suggested number of items to load.

Returns
List<Value> List of items, in descending order, starting after the specified item. Null if the data source is no longer valid, and should not be queried again.

loadInitial

List<Value> loadInitial (int pageSize)

Parameters
pageSize int

Returns
List<Value>

This site uses cookies to store your preferences for site-specific language and display options.

Get the latest Android developer news and tips that will help you find success on Google Play.

* Required Fields

Hooray!

Browse this site in ?

You requested a page in , but your language preference for this site is .

Would you like to change your language preference and browse this site in ? If you want to change your language preference later, use the language menu at the bottom of each page.

This class requires API level or higher

This doc is hidden because your selected API level for the documentation is . You can change the documentation API level with the selector above the left navigation.

For more information about specifying the API level your app requires, read Supporting Different Platform Versions.

Take a short survey?
Help us improve the Android developer experience.
(Sep 2017 survey)