Merge "Switch DataSources to be async to better support network usecase" into oc-mr1-support-27.0-dev
diff --git a/paging/common/src/main/java/android/arch/paging/BoundedDataSource.java b/paging/common/src/main/java/android/arch/paging/BoundedDataSource.java
deleted file mode 100644
index 0656490..0000000
--- a/paging/common/src/main/java/android/arch/paging/BoundedDataSource.java
+++ /dev/null
@@ -1,80 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.arch.paging;
-
-import android.support.annotation.Nullable;
-import android.support.annotation.RestrictTo;
-import android.support.annotation.WorkerThread;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * Simplest data source form that provides all of its data through a single loadRange() method.
- * <p>
- * Requires that your data resides in positions <code>0</code> through <code>N</code>, where
- * <code>N</code> is the value returned from {@link #countItems()}. You must return the exact number
- * requested, so that the data as returned can be safely prepended/appended to what has already
- * been loaded.
- * <p>
- * For more flexibility in how many items to load, or to avoid counting your data source, override
- * {@link PositionalDataSource} directly.
- *
- * @param <Value> Value type returned by the data source.
- *
- * @hide
- */
-@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
-public abstract class BoundedDataSource<Value> extends PositionalDataSource<Value> {
- /**
- * Called to load items at from the specified position range.
- *
- * @param startPosition Index of first item to load.
- * @param loadCount Exact number of items to load. Returning a different number will cause
- * an exception to be thrown.
- * @return List of loaded items. Null if the BoundedDataSource is no longer valid, and should
- * not be queried again.
- */
- @WorkerThread
- @Nullable
- public abstract List<Value> loadRange(int startPosition, int loadCount);
-
- @WorkerThread
- @Nullable
- @Override
- public List<Value> loadAfter(int startIndex, int pageSize) {
- return loadRange(startIndex, pageSize);
- }
-
- @WorkerThread
- @Nullable
- @Override
- public List<Value> loadBefore(int startIndex, int pageSize) {
- if (startIndex < 0) {
- return new ArrayList<>();
- }
- int loadSize = Math.min(pageSize, startIndex + 1);
- startIndex = startIndex - loadSize + 1;
- List<Value> result = loadRange(startIndex, loadSize);
- if (result != null) {
- if (result.size() != loadSize) {
- throw new IllegalStateException("invalid number of items returned.");
- }
- }
- return result;
- }
-}
diff --git a/paging/common/src/main/java/android/arch/paging/ContiguousDataSource.java b/paging/common/src/main/java/android/arch/paging/ContiguousDataSource.java
index 414c4ff..03f2e86 100644
--- a/paging/common/src/main/java/android/arch/paging/ContiguousDataSource.java
+++ b/paging/common/src/main/java/android/arch/paging/ContiguousDataSource.java
@@ -19,44 +19,21 @@
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
-import java.util.List;
-
abstract class ContiguousDataSource<Key, Value> extends DataSource<Key, Value> {
@Override
boolean isContiguous() {
return true;
}
- abstract void loadInitial(Key key, int initialLoadSize, boolean enablePlaceholders,
- @NonNull PageResult.Receiver<Key, Value> receiver);
+ public abstract void loadInitial(@Nullable Key key, int initialLoadSize,
+ boolean enablePlaceholders,
+ @NonNull InitialLoadCallback<Value> callback);
- void loadAfter(int currentEndIndex, @NonNull Value currentEndItem, int pageSize,
- @NonNull PageResult.Receiver<Key, Value> receiver) {
- if (!isInvalid()) {
- List<Value> list = loadAfterImpl(currentEndIndex, currentEndItem, pageSize);
+ abstract void loadAfter(int currentEndIndex, @NonNull Value currentEndItem, int pageSize,
+ @NonNull LoadCallback<Value> callback);
- if (list != null && !isInvalid()) {
- receiver.postOnPageResult(new PageResult<>(
- PageResult.APPEND, new Page<Key, Value>(list), 0, 0, 0));
- return;
- }
- }
- receiver.postOnPageResult(new PageResult<Key, Value>(PageResult.APPEND));
- }
-
- void loadBefore(int currentBeginIndex, @NonNull Value currentBeginItem, int pageSize,
- @NonNull PageResult.Receiver<Key, Value> receiver) {
- if (!isInvalid()) {
- List<Value> list = loadBeforeImpl(currentBeginIndex, currentBeginItem, pageSize);
-
- if (list != null && !isInvalid()) {
- receiver.postOnPageResult(new PageResult<>(
- PageResult.PREPEND, new Page<Key, Value>(list), 0, 0, 0));
- return;
- }
- }
- receiver.postOnPageResult(new PageResult<Key, Value>(PageResult.PREPEND));
- }
+ abstract void loadBefore(int currentBeginIndex, @NonNull Value currentBeginItem, int pageSize,
+ @NonNull LoadCallback<Value> callback);
/**
* Get the key from either the position, or item, or null if position/item invalid.
@@ -65,12 +42,4 @@
* that isn't yet loaded, a fallback item (last loaded item accessed) will be passed.
*/
abstract Key getKey(int position, Value item);
-
- @Nullable
- abstract List<Value> loadAfterImpl(int currentEndIndex,
- @NonNull Value currentEndItem, int pageSize);
-
- @Nullable
- abstract List<Value> loadBeforeImpl(int currentBeginIndex,
- @NonNull Value currentBeginItem, int pageSize);
}
diff --git a/paging/common/src/main/java/android/arch/paging/ContiguousPagedList.java b/paging/common/src/main/java/android/arch/paging/ContiguousPagedList.java
index cdff391..bd1bb37 100644
--- a/paging/common/src/main/java/android/arch/paging/ContiguousPagedList.java
+++ b/paging/common/src/main/java/android/arch/paging/ContiguousPagedList.java
@@ -21,6 +21,7 @@
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
+import java.util.List;
import java.util.concurrent.Executor;
class ContiguousPagedList<K, V> extends PagedList<V> implements PagedStorage.Callback {
@@ -31,28 +32,13 @@
private int mPrependItemsRequested = 0;
private int mAppendItemsRequested = 0;
- @SuppressWarnings("unchecked")
- private final PagedStorage<K, V> mKeyedStorage = (PagedStorage<K, V>) mStorage;
-
- private final PageResult.Receiver<K, V> mReceiver = new PageResult.Receiver<K, V>() {
- @AnyThread
- @Override
- public void postOnPageResult(@NonNull final PageResult<K, V> pageResult) {
- // NOTE: if we're already on main thread, this can delay page receive by a frame
- mMainThreadExecutor.execute(new Runnable() {
- @Override
- public void run() {
- onPageResult(pageResult);
- }
- });
- }
-
+ private PageResult.Receiver<V> mReceiver = new PageResult.Receiver<V>() {
// Creation thread for initial synchronous load, otherwise main thread
// Safe to access main thread only state - no other thread has reference during construction
@AnyThread
@Override
- public void onPageResult(@NonNull PageResult<K, V> pageResult) {
- if (pageResult.page == null) {
+ public void onPageResult(int type, @NonNull PageResult<V> pageResult) {
+ if (pageResult.isInvalid()) {
detach();
return;
}
@@ -62,25 +48,30 @@
return;
}
- Page<K, V> page = pageResult.page;
- if (pageResult.type == PageResult.INIT) {
- mKeyedStorage.init(pageResult.leadingNulls, page, pageResult.trailingNulls,
+ List<V> page = pageResult.page;
+ if (type == PageResult.INIT) {
+ mStorage.init(pageResult.leadingNulls, page, pageResult.trailingNulls,
pageResult.positionOffset, ContiguousPagedList.this);
- notifyInserted(0, mKeyedStorage.size());
- } else if (pageResult.type == PageResult.APPEND) {
- mKeyedStorage.appendPage(page, ContiguousPagedList.this);
- } else if (pageResult.type == PageResult.PREPEND) {
- mKeyedStorage.prependPage(page, ContiguousPagedList.this);
+
+ // notifyInserted is safe here, since if we're not on main thread, we won't have any
+ // Callbacks registered to listen to the notify.
+ notifyInserted(0, mStorage.size());
+
+ mLastLoad = pageResult.leadingNulls + pageResult.positionOffset + page.size() / 2;
+ } else if (type == PageResult.APPEND) {
+ mStorage.appendPage(page, ContiguousPagedList.this);
+ } else if (type == PageResult.PREPEND) {
+ mStorage.prependPage(page, ContiguousPagedList.this);
}
if (mBoundaryCallback != null) {
boolean deferEmpty = mStorage.size() == 0;
boolean deferBegin = !deferEmpty
- && pageResult.type == PageResult.PREPEND
- && pageResult.page.items.size() == 0;
+ && type == PageResult.PREPEND
+ && pageResult.page.size() == 0;
boolean deferEnd = !deferEmpty
- && pageResult.type == PageResult.APPEND
- && pageResult.page.items.size() == 0;
+ && type == PageResult.APPEND
+ && pageResult.page.size() == 0;
deferBoundaryCallbacks(deferEmpty, deferBegin, deferEnd);
}
}
@@ -93,24 +84,32 @@
@Nullable BoundaryCallback<V> boundaryCallback,
@NonNull Config config,
final @Nullable K key) {
- super(new PagedStorage<K, V>(), mainThreadExecutor, backgroundThreadExecutor,
+ super(new PagedStorage<V>(), mainThreadExecutor, backgroundThreadExecutor,
boundaryCallback, config);
mDataSource = dataSource;
- // blocking init just triggers the initial load on the construction thread -
- // Could still be posted with callback, if desired.
- mDataSource.loadInitial(key,
- mConfig.initialLoadSizeHint,
- mConfig.enablePlaceholders,
- mReceiver);
+ if (mDataSource.isInvalid()) {
+ detach();
+ } else {
+ DataSource.InitialLoadCallback<V> callback = new DataSource.InitialLoadCallback<>(
+ mConfig.enablePlaceholders, mDataSource, mReceiver);
+ mDataSource.loadInitial(key,
+ mConfig.initialLoadSizeHint,
+ mConfig.enablePlaceholders,
+ callback);
+
+ // If initialLoad's callback is not called within the body, we force any following calls
+ // to post to the UI thread. This constructor may be run on a background thread, but
+ // after constructor, mutation must happen on UI thread.
+ callback.setPostExecutor(mMainThreadExecutor);
+ }
}
@MainThread
@Override
void dispatchUpdatesSinceSnapshot(
@NonNull PagedList<V> pagedListSnapshot, @NonNull Callback callback) {
-
- final PagedStorage<?, V> snapshot = pagedListSnapshot.mStorage;
+ final PagedStorage<V> snapshot = pagedListSnapshot.mStorage;
final int newlyAppended = mStorage.getNumberAppended() - snapshot.getNumberAppended();
final int newlyPrepended = mStorage.getNumberPrepended() - snapshot.getNumberPrepended();
@@ -120,7 +119,8 @@
// Validate that the snapshot looks like a previous version of this list - if it's not,
// we can't be sure we'll dispatch callbacks safely
- if (newlyAppended < 0
+ if (snapshot.isEmpty()
+ || newlyAppended < 0
|| newlyPrepended < 0
|| mStorage.getTrailingNullCount() != Math.max(previousTrailing - newlyAppended, 0)
|| mStorage.getLeadingNullCount() != Math.max(previousLeading - newlyPrepended, 0)
@@ -190,7 +190,14 @@
if (isDetached()) {
return;
}
- mDataSource.loadBefore(position, item, mConfig.pageSize, mReceiver);
+ if (mDataSource.isInvalid()) {
+ detach();
+ } else {
+ DataSource.LoadCallback<V> callback = new DataSource.LoadCallback<>(
+ PageResult.PREPEND, mMainThreadExecutor, mDataSource, mReceiver);
+ mDataSource.loadBefore(position, item, mConfig.pageSize, callback);
+ }
+
}
});
}
@@ -213,7 +220,13 @@
if (isDetached()) {
return;
}
- mDataSource.loadAfter(position, item, mConfig.pageSize, mReceiver);
+ if (mDataSource.isInvalid()) {
+ detach();
+ } else {
+ DataSource.LoadCallback<V> callback = new DataSource.LoadCallback<>(
+ PageResult.APPEND, mMainThreadExecutor, mDataSource, mReceiver);
+ mDataSource.loadAfter(position, item, mConfig.pageSize, callback);
+ }
}
});
}
diff --git a/paging/common/src/main/java/android/arch/paging/DataSource.java b/paging/common/src/main/java/android/arch/paging/DataSource.java
index ff44521..994661a 100644
--- a/paging/common/src/main/java/android/arch/paging/DataSource.java
+++ b/paging/common/src/main/java/android/arch/paging/DataSource.java
@@ -20,26 +20,68 @@
import android.support.annotation.NonNull;
import android.support.annotation.WorkerThread;
+import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
+import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicBoolean;
/**
- * Base class for incremental data loading, used in list paging. To implement, extend either the
- * {@link KeyedDataSource}, or {@link TiledDataSource} subclass.
+ * Base class for loading pages of snapshot data into a {@link PagedList}.
* <p>
- * Choose based on whether each load operation is based on the position of the data in the list.
+ * DataSource is queried to load pages of content into a {@link PagedList}. A PagedList can grow as
+ * it loads more data, but the data loaded cannot be updated.
* <p>
- * Use {@link KeyedDataSource} if you need to use data from item <code>N-1</code> to load item
- * <code>N</code>. For example, if requesting the backend for the next comments in the list
+ * A PagedList / DataSource pair serve as a snapshot of the data set being loaded. If the
+ * underlying data set is modified, a new PagedList / DataSource pair must be created to represent
+ * the new data.
+ * <h4>Loading Pages</h4>
+ * PagedList queries data from its DataSource in response to loading hints. {@link PagedListAdapter}
+ * calls {@link PagedList#loadAround(int)} to load content as the user scrolls in a RecyclerView.
+ * <p>
+ * To control how and when a PagedList queries data from its DataSource, see
+ * {@link PagedList.Config}. The Config object defines things like load sizes and prefetch distance.
+ * <h4>Updating Paged Data</h4>
+ * A PagedList / DataSource pair are a snapshot of the data set. A new pair of
+ * PagedList / DataSource must be created if an update occurs, such as a reorder, insert, delete, or
+ * content update occurs. A DataSource must detect that it cannot continue loading its
+ * snapshot (for instance, when Database query notices a table being invalidated), and call
+ * {@link #invalidate()}. Then a new PagedList / DataSource pair would be created to load data from
+ * the new state of the Database query.
+ * <p>
+ * To page in data that doesn't update, you can create a single DataSource, and pass it to a single
+ * PagedList. For example, loading from network when the network's paging API doesn't provide
+ * updates.
+ * <p>
+ * To page in data from a source that does provide updates, you can create a
+ * {@link DataSource.Factory}, where each DataSource created is invalidated when an update to the
+ * data set occurs that makes the current snapshot invalid. For example, when paging a query from
+ * the Database, and the table being queried inserts or removes items. You can also use a
+ * DataSource.Factory to provide multiple versions of network-paged lists. If reloading all content
+ * (e.g. in response to an action like swipe-to-refresh) is required to get a new version of data,
+ * you can connect an explicit refresh signal to call {@link #invalidate()} on the current
+ * DataSource.
+ * <p>
+ * If you have more granular update signals, such as a network API signaling an update to a single
+ * item in the list, it's recommended to load data from network into memory. Then present that
+ * data to the PagedList via a DataSource that wraps an in-memory snapshot. Each time the in-memory
+ * copy changes, invalidate the previous DataSource, and a new one wrapping the new state of the
+ * snapshot can be created.
+ * <h4>Implementing a DataSource</h4>
+ * To implement, extend either the {@link KeyedDataSource}, or {@link PositionalDataSource}
+ * subclass. Choose based on whether each load operation is based on the position of the data in the
+ * list.
+ * <p>
+ * Use {@link KeyedDataSource} if you need to use data from item {@code N-1} to load item
+ * {@code N}. For example, if requesting the backend for the next comments in the list
* requires the ID or timestamp of the most recent loaded comment, or if querying the next users
* from a name-sorted database query requires the name and unique ID of the previous.
* <p>
- * Use {@link TiledDataSource} if you can load arbitrary pages based solely on position information,
- * and can provide a fixed item count. TiledDataSource supports querying pages at arbitrary
- * positions, so can provide data to PagedLists in arbitrary order.
+ * Use {@link PositionalDataSource} if you can load arbitrary pages based solely on position
+ * information, and can provide a fixed item count. PositionalDataSource supports querying pages at
+ * arbitrary positions, so can provide data to PagedLists in arbitrary order.
* <p>
- * Because a <code>null</code> item indicates a placeholder in {@link PagedList}, DataSource may not
- * return <code>null</code> items in lists that it loads. This is so that users of the PagedList
+ * Because a {@code null} item indicates a placeholder in {@link PagedList}, DataSource may not
+ * return {@code null} items in lists that it loads. This is so that users of the PagedList
* can differentiate unloaded placeholder items from content that has been paged in.
*
* @param <Key> Input used to trigger initial load from the DataSource. Often an Integer position.
@@ -47,8 +89,36 @@
*/
@SuppressWarnings("unused") // suppress warning to remove Key/Value, needed for subclass type safety
public abstract class DataSource<Key, Value> {
-
+ /**
+ * Factory for DataSources.
+ * <p>
+ * Data-loading systems of an application or library can implement this interface to allow
+ * {@code LiveData<PagedList>}s to be created. For example, Room can provide a
+ * DataSource.Factory for a given SQL query:
+ *
+ * <pre>
+ * {@literal @}Dao
+ * interface UserDao {
+ * {@literal @}Query("SELECT * FROM user ORDER BY lastName ASC")
+ * public abstract DataSource.Factory<Integer, User> usersByLastName();
+ * }
+ * </pre>
+ * In the above sample, {@code Integer} is used because it is the {@code Key} type of
+ * PositionalDataSource. Currently, Room uses the {@code LIMIT}/{@code OFFSET} SQL keywords to
+ * page a large query with a PositionalDataSource.
+ *
+ * @param <Key> Key identifying items in DataSource.
+ * @param <Value> Type of items in the list loaded by the DataSources.
+ */
public interface Factory<Key, Value> {
+ /**
+ * Create a DataSource.
+ * <p>
+ * The DataSource should invalidate itself if the snapshot is no longer valid, and a new
+ * DataSource should be queried from the Factory.
+ *
+ * @return the new DataSource.
+ */
DataSource<Key, Value> create();
}
@@ -58,19 +128,168 @@
}
/**
- * If returned by countItems(), indicates an undefined number of items are provided by the data
- * source. Continued querying in either direction may continue to produce more data.
- */
- @SuppressWarnings("WeakerAccess")
- public static int COUNT_UNDEFINED = -1;
-
- /**
* Returns true if the data source guaranteed to produce a contiguous set of items,
* never producing gaps.
*/
abstract boolean isContiguous();
/**
+ * Callback for DataSource initial loading methods to return data and position/count
+ * information.
+ * <p>
+ * A callback can be called only once, and will throw if called again.
+ * <p>
+ * It is always valid for a DataSource loading method that takes a callback to stash the
+ * callback and call it later. This enables DataSources to be fully asynchronous, and to handle
+ * temporary, recoverable error states (such as a network error that can be retried).
+ *
+ * @param <T> Type of items being loaded.
+ */
+ public static class InitialLoadCallback<T> extends LoadCallback<T> {
+ InitialLoadCallback(boolean acceptCount,
+ DataSource dataSource, PageResult.Receiver<T> receiver) {
+ super(PageResult.INIT, acceptCount, dataSource, receiver);
+ }
+
+ /**
+ * Called to pass initial load state from a DataSource.
+ * <p>
+ * Call this method from your DataSource's {@code loadInitial} function to return data,
+ * and inform how many placeholders should be shown before and after. If counting is cheap
+ * to compute (for example, if a network load returns the information regardless), it's
+ * recommended to pass data back through this method.
+ *
+ * @param data List of items loaded from the DataSource. If this is empty, the DataSource
+ * is treated as empty, and no further loads will occur.
+ * @param position Position of the item at the front of the list, relative to the total
+ * count. If there are {@code N} items before the items in data that can be
+ * loaded from this DataSource, pass {@code N}.
+ * @param totalCount Total number of items that may be returned from this DataSource.
+ * Includes the number in the initial {@code data} parameter
+ * as well as any items that can be loaded in front or behind of
+ * {@code data}.
+ */
+ public void onResult(@NonNull List<T> data, int position, int totalCount) {
+ int trailingUnloadedCount = totalCount - position - data.size();
+ if (mAcceptCount) {
+ dispatchResultToReceiver(new PageResult<>(
+ data, position, trailingUnloadedCount, 0));
+ } else {
+ dispatchResultToReceiver(new PageResult<>(data, position));
+ }
+ }
+
+ /**
+ * Called to pass initial load state from a DataSource without supporting placeholders.
+ * <p>
+ * Call this method from your DataSource's {@code loadInitial} function to return data,
+ * if position is known but total size is not. If counting is not expensive, consider
+ * calling the three parameter variant: {@link #onResult(List, int, int)}.
+ *
+ * @param data List of items loaded from the DataSource. If this is empty, the DataSource
+ * is treated as empty, and no further loads will occur.
+ * @param position Position of the item at the front of the list. If there are {@code N}
+ * items before the items in data that can be provided by this DataSource,
+ * pass {@code N}.
+ */
+ void onResult(@NonNull List<T> data, int position) {
+ // not counting, don't need to check mAcceptCount
+ dispatchResultToReceiver(new PageResult<>(
+ data, 0, 0, position));
+ }
+ }
+
+ /**
+ * Callback for DataSource loading methods to return data.
+ * <p>
+ * A callback can be called only once, and will throw if called again.
+ * <p>
+ * It is always valid for a DataSource loading method that takes a callback to stash the
+ * callback and call it later. This enables DataSources to be fully asynchronous, and to handle
+ * temporary, recoverable error states (such as a network error that can be retried).
+ *
+ * @param <T> Type of items being loaded.
+ */
+ public static class LoadCallback<T> {
+ final boolean mAcceptCount;
+ final int mType;
+ private final DataSource mDataSource;
+ private final PageResult.Receiver<T> mReceiver;
+
+ private int mPositionOffset = 0;
+
+ // mSignalLock protects mPostExecutor, and mHasSignalled
+ private final Object mSignalLock = new Object();
+ private Executor mPostExecutor = null;
+ private boolean mHasSignalled = false;
+
+ private LoadCallback(int type, boolean acceptCount,
+ DataSource dataSource, PageResult.Receiver<T> receiver) {
+ mType = type;
+ mAcceptCount = acceptCount;
+ mDataSource = dataSource;
+ mReceiver = receiver;
+ }
+
+ LoadCallback(int type, Executor mainThreadExecutor,
+ DataSource dataSource, PageResult.Receiver<T> receiver) {
+ mType = type;
+ mAcceptCount = false;
+ mPostExecutor = mainThreadExecutor;
+ mDataSource = dataSource;
+ mReceiver = receiver;
+ }
+
+ void setPositionOffset(int positionOffset) {
+ mPositionOffset = positionOffset;
+ }
+
+ void setPostExecutor(Executor postExecutor) {
+ synchronized (mSignalLock) {
+ mPostExecutor = postExecutor;
+ }
+ }
+
+ /**
+ * Called to pass loaded data from a DataSource.
+ * <p>
+ * Call this method from your DataSource's {@code load} methods to return data.
+ *
+ * @param data List of items loaded from the DataSource.
+ */
+ public void onResult(@NonNull List<T> data) {
+ dispatchResultToReceiver(new PageResult<>(
+ data, 0, 0, mPositionOffset));
+ }
+
+ void dispatchResultToReceiver(final @NonNull PageResult<T> result) {
+ Executor executor;
+ synchronized (mSignalLock) {
+ if (mHasSignalled) {
+ throw new IllegalStateException(
+ "LoadCallback already dispatched, cannot dispatch again.");
+ }
+ mHasSignalled = true;
+ executor = mPostExecutor;
+ }
+
+ final PageResult<T> resolvedResult =
+ mDataSource.isInvalid() ? PageResult.<T>getInvalidResult() : result;
+
+ if (executor != null) {
+ executor.execute(new Runnable() {
+ @Override
+ public void run() {
+ mReceiver.onPageResult(mType, result);
+ }
+ });
+ } else {
+ mReceiver.onPageResult(mType, result);
+ }
+ }
+ }
+
+ /**
* Invalidation callback for DataSource.
* <p>
* Used to signal when a DataSource a data source has become invalid, and that a new data source
diff --git a/paging/common/src/main/java/android/arch/paging/KeyedDataSource.java b/paging/common/src/main/java/android/arch/paging/KeyedDataSource.java
index 3214a4e..b6656f3 100644
--- a/paging/common/src/main/java/android/arch/paging/KeyedDataSource.java
+++ b/paging/common/src/main/java/android/arch/paging/KeyedDataSource.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -16,223 +16,127 @@
package android.arch.paging;
-import android.support.annotation.AnyThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
-import android.support.annotation.WorkerThread;
-import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
-
/**
* Incremental data loader for paging keyed content, where loaded content uses previously loaded
* items as input to future loads.
* <p>
- * Implement a DataSource using KeyedDataSource if you need to use data from item <code>N-1</code>
- * to load item <code>N</code>. This is common, for example, in sorted database queries where
+ * Implement a DataSource using KeyedDataSource if you need to use data from item {@code N - 1}
+ * to load item {@code 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.
- * <p>
- * 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):
- * <pre>
- * {@literal @}Dao
- * interface UserDao {
- * {@literal @}Query("SELECT * from user ORDER BY name DESC LIMIT :limit")
- * public abstract List<User> userNameInitial(int limit);
- *
- * {@literal @}Query("SELECT * from user WHERE name < :key ORDER BY name DESC LIMIT :limit")
- * public abstract List<User> userNameLoadAfter(String key, int limit);
- *
- * {@literal @}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;
- * {@literal @}SuppressWarnings("FieldCanBeLocal")
- * private final InvalidationTracker.Observer mObserver;
- *
- * public KeyedUserQueryDataSource(MyDatabase db) {
- * mDb = db;
- * mUserDao = db.getUserDao();
- * mObserver = new InvalidationTracker.Observer("user") {
- * {@literal @}Override
- * public void onInvalidated({@literal @}NonNull Set<String> tables) {
- * // the user table has been invalidated, invalidate the DataSource
- * invalidate();
- * }
- * };
- * db.getInvalidationTracker().addWeakObserver(mObserver);
- * }
- *
- * {@literal @}Override
- * public boolean isInvalid() {
- * mDb.getInvalidationTracker().refreshVersionsSync();
- * return super.isInvalid();
- * }
- *
- * {@literal @}Override
- * public String getKey({@literal @}NonNull User item) {
- * return item.getName();
- * }
- *
- * {@literal @}Override
- * public List<User> loadInitial(int pageSize) {
- * return mUserDao.userNameInitial(pageSize);
- * }
- *
- * {@literal @}Override
- * public List<User> loadBefore({@literal @}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);
- * }
- *
- * {@literal @}Override
- * public List<User> loadAfter({@literal @}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);
- * }
- * }</pre>
*
* @param <Key> Type of data used to query Value types out of the DataSource.
* @param <Value> Type of items being loaded by the DataSource.
*/
public abstract class KeyedDataSource<Key, Value> extends ContiguousDataSource<Key, Value> {
-
- @Nullable
@Override
- List<Value> loadAfterImpl(int currentEndIndex, @NonNull Value currentEndItem, int pageSize) {
- return loadAfter(getKey(currentEndItem), pageSize);
+ final void loadAfter(int currentEndIndex, @NonNull Value currentEndItem, int pageSize,
+ @NonNull LoadCallback<Value> callback) {
+ loadAfter(getKey(currentEndItem), pageSize, callback);
+ }
+
+ @Override
+ final void loadBefore(int currentBeginIndex, @NonNull Value currentBeginItem, int pageSize,
+ @NonNull LoadCallback<Value> callback) {
+ loadBefore(getKey(currentBeginItem), pageSize, callback);
}
@Nullable
@Override
- List<Value> loadBeforeImpl(
- int currentBeginIndex, @NonNull Value currentBeginItem, int pageSize) {
- List<Value> list = loadBefore(getKey(currentBeginItem), pageSize);
-
- if (list != null && list.size() > 1) {
- // TODO: move out of keyed entirely, into the DB DataSource.
- list = new ArrayList<>(list);
- Collections.reverse(list);
+ final Key getKey(int position, Value item) {
+ if (item == null) {
+ return null;
}
- return list;
+
+ return getKey(item);
}
- @Override
- void loadInitial(Key key, int initialLoadSize, boolean enablePlaceholders,
- @NonNull PageResult.Receiver<Key, Value> receiver) {
-
- PageResult<Key, Value> pageResult =
- loadInitialInternal(key, initialLoadSize, enablePlaceholders);
- if (pageResult == null) {
- // loading failed, return empty page
- receiver.onPageResult(new PageResult<Key, Value>(PageResult.INIT));
- } else {
- receiver.onPageResult(pageResult);
- }
- }
-
/**
- * Try initial load, and either return the successful initial load to the receiver,
- * or null if unsuccessful.
+ * Load initial data.
+ * <p>
+ * This method is called first to initialize a PagedList with data. If it's possible to count
+ * the items that can be loaded by the DataSource, it's recommended to pass the loaded data to
+ * the callback via the three-parameter
+ * {@link DataSource.InitialLoadCallback#onResult(List, int, int)}. This enables PagedLists
+ * presenting data from this source to display placeholders to represent unloaded items.
+ * <p>
+ * {@code initialLoadKey} and {@code requestedLoadSize} are hints, not requirements, so if it is
+ * difficult or impossible to respect them, they may be altered. Note that ignoring the
+ * {@code initialLoadKey} can prevent subsequent PagedList/DataSource pairs from initializing at
+ * the same location. If your data source never invalidates (for example, loading from the
+ * network without the network ever signalling that old data must be reloaded), it's fine to
+ * ignore the {@code initialLoadKey} and always start from the beginning of the data set.
+ *
+ * @param initialLoadKey Load items around this key, or at the beginning of the data set if null
+ * is passed.
+ * @param requestedLoadSize Suggested number of items to load.
+ * @param enablePlaceholders Signals whether counting is requested. If false, you can
+ * potentially save work by calling the single-parameter variant of
+ * {@link DataSource.LoadCallback#onResult(List)} and not counting the
+ * number of items in the data set.
+ * @param callback DataSource.LoadCallback that receives initial load data.
*/
- @Nullable
- private PageResult<Key, Value> loadInitialInternal(
- @Nullable Key key, int initialLoadSize, boolean enablePlaceholders) {
- // check if invalid at beginning, and before returning a valid list
- if (isInvalid()) {
- return null;
- }
+ @Override
+ public abstract void loadInitial(@Nullable Key initialLoadKey, int requestedLoadSize,
+ boolean enablePlaceholders, @NonNull InitialLoadCallback<Value> callback);
- List<Value> list;
- if (key == null) {
- // no key, so load initial.
- list = loadInitial(initialLoadSize);
- if (list == null) {
- return null;
- }
- } else {
- List<Value> after = loadAfter(key, initialLoadSize / 2);
- if (after == null) {
- return null;
- }
+ /**
+ * Load list data after the specified item.
+ * <p>
+ * 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.
+ * <p>
+ * Data may be passed synchronously during the loadAfter method, or deferred and called at a
+ * later time. Further loads going down will be blocked until the callback is called.
+ * <p>
+ * If data cannot be loaded (for example, if the request is invalid, or the data would be stale
+ * and inconsistent, it is valid to call {@link #invalidate()} to invalidate the data source,
+ * and prevent further loading.
+ *
+ * @param currentEndKey Load items after this key. May be null on initial load, to indicate load
+ * from beginning.
+ * @param pageSize Suggested number of items to load.
+ * @param callback DataSource.LoadCallback that receives loaded data.
+ */
+ public abstract void loadAfter(@NonNull Key currentEndKey, int pageSize,
+ @NonNull LoadCallback<Value> callback);
- Key loadBeforeKey = after.isEmpty() ? key : getKey(after.get(0));
- List<Value> before = loadBefore(loadBeforeKey, initialLoadSize / 2);
- if (before == null) {
- return null;
- }
- if (!after.isEmpty() || !before.isEmpty()) {
- // one of the lists has data
- if (after.isEmpty()) {
- // retry loading after, since it may be that the key passed points to the end of
- // the list, so we need to load after the last item in the before list
- after = loadAfter(getKey(before.get(0)), initialLoadSize / 2);
- if (after == null) {
- return null;
- }
- }
- // assemble full list
- list = new ArrayList<>();
- list.addAll(before);
- // Note - we reverse the list instead of before, in case before is immutable
- Collections.reverse(list);
- list.addAll(after);
- } else {
- // load before(key) and load after(key) failed - try load initial to be *sure* we
- // catch the case where there's only one item, which is loaded by the key case
- list = loadInitial(initialLoadSize);
- if (list == null) {
- return null;
- }
- }
- }
-
- final Page<Key, Value> page = new Page<>(list);
-
- if (list.isEmpty()) {
- if (isInvalid()) {
- return null;
- }
- // wasn't able to load any items, but not invalid - return an empty page.
- return new PageResult<>(PageResult.INIT, page, 0, 0, 0);
- }
-
- int itemsBefore = COUNT_UNDEFINED;
- int itemsAfter = COUNT_UNDEFINED;
- if (enablePlaceholders) {
- itemsBefore = countItemsBefore(getKey(list.get(0)));
- itemsAfter = countItemsAfter(getKey(list.get(list.size() - 1)));
- }
-
- if (isInvalid()) {
- return null;
- }
- if (itemsBefore == COUNT_UNDEFINED || itemsAfter == COUNT_UNDEFINED) {
- itemsBefore = 0;
- itemsAfter = 0;
- }
- return new PageResult<>(
- PageResult.INIT,
- page,
- itemsBefore,
- itemsAfter,
- 0);
- }
+ /**
+ * Load data before the currently loaded content.
+ * <p>
+ * 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 that the last
+ * item returned must be directly adjacent to the key passed, so varying size from the pageSize
+ * requested should effectively grow or shrink the list by modifying the beginning, not the end.
+ * <p>
+ * Data may be passed synchronously during the loadBefore method, or deferred and called at a
+ * later time. Further loads going up will be blocked until the callback is called.
+ * <p>
+ * If data cannot be loaded (for example, if the request is invalid, or the data would be stale
+ * and inconsistent, it is valid to call {@link #invalidate()} to invalidate the data source,
+ * and prevent further loading.
+ * <p class="note"><strong>Note:</strong> Data must be returned in the order it will be
+ * presented in the list.
+ *
+ * @param currentBeginKey Load items before this key.
+ * @param pageSize Suggested number of items to load.
+ * @param callback DataSource.LoadCallback that receives loaded data.
+ */
+ public abstract void loadBefore(@NonNull Key currentBeginKey, int pageSize,
+ @NonNull LoadCallback<Value> callback);
/**
* Return a key associated with the given item.
* <p>
* If your KeyedDataSource is loading from a source that is sorted and loaded by a unique
* integer ID, you would return {@code item.getID()} here. This key can then be passed to
- * {@link #loadBefore(Key, int)} or {@link #loadAfter(Key, int)} to load additional items
- * adjacent to the item passed to this function.
+ * {@link #loadBefore(Object, int, LoadCallback)} or
+ * {@link #loadAfter(Object, int, LoadCallback)} to load additional items adjacent to the item
+ * passed to this function.
* <p>
* 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,
@@ -243,101 +147,5 @@
* @return Key associated with given item.
*/
@NonNull
- @AnyThread
public abstract Key getKey(@NonNull Value item);
-
- /**
- * Return the number of items that occur before the item uniquely identified by {@code key} in
- * the data set.
- * <p>
- * For example, if you're loading items sorted by ID, then this would return the total number of
- * items with ID less than {@code key}.
- * <p>
- * If you return {@link #COUNT_UNDEFINED} here, or from {@link #countItemsAfter(Key)}, your
- * data source will not present placeholder null items in place of unloaded data.
- *
- * @param key A unique identifier of an item in the data set.
- * @return Number of items in the data set before the item identified by {@code key}, or
- * {@link #COUNT_UNDEFINED}.
- *
- * @see #countItemsAfter(Key)
- */
- @WorkerThread
- public int countItemsBefore(@NonNull Key key) {
- return COUNT_UNDEFINED;
- }
-
- /**
- * Return the number of items that occur after the item uniquely identified by {@code key} in
- * the data set.
- * <p>
- * For example, if you're loading items sorted by ID, then this would return the total number of
- * items with ID greater than {@code key}.
- * <p>
- * If you return {@link #COUNT_UNDEFINED} here, or from {@link #countItemsBefore(Key)}, your
- * data source will not present placeholder null items in place of unloaded data.
- *
- * @param key A unique identifier of an item in the data set.
- * @return Number of items in the data set after the item identified by {@code key}, or
- * {@link #COUNT_UNDEFINED}.
- *
- * @see #countItemsBefore(Key)
- */
- @WorkerThread
- public int countItemsAfter(@NonNull Key key) {
- return COUNT_UNDEFINED;
- }
-
- @WorkerThread
- @Nullable
- public abstract List<Value> loadInitial(int pageSize);
-
- /**
- * Load list data after the specified item.
- * <p>
- * 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.
- *
- * @param currentEndKey Load items after this key. May be null on initial load, to indicate load
- * from beginning.
- * @param pageSize Suggested number of items to load.
- * @return List of items, starting after the specified item. Null if the data source is
- * no longer valid, and should not be queried again.
- */
- @SuppressWarnings("WeakerAccess")
- @WorkerThread
- @Nullable
- public abstract List<Value> loadAfter(@NonNull Key currentEndKey, int pageSize);
-
- /**
- * Load data before the currently loaded content, starting at the provided index,
- * in reverse-display order.
- * <p>
- * 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.
- * <p class="note"><strong>Note:</strong> Items returned from loadBefore <em>must</em> 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 {@code pageSize} by
- * shortening or lengthening the return list as it desires.
- * <p>
- *
- * @param currentBeginKey Load items before this key.
- * @param pageSize Suggested number of items to load.
- * @return 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.
- */
- @SuppressWarnings("WeakerAccess")
- @WorkerThread
- @Nullable
- public abstract List<Value> loadBefore(@NonNull Key currentBeginKey, int pageSize);
-
- @Nullable
- @Override
- Key getKey(int position, Value item) {
- if (item == null) {
- return null;
- }
- return getKey(item);
- }
}
diff --git a/paging/common/src/main/java/android/arch/paging/ListDataSource.java b/paging/common/src/main/java/android/arch/paging/ListDataSource.java
index d3a171e..b6f366a 100644
--- a/paging/common/src/main/java/android/arch/paging/ListDataSource.java
+++ b/paging/common/src/main/java/android/arch/paging/ListDataSource.java
@@ -16,10 +16,12 @@
package android.arch.paging;
+import android.support.annotation.NonNull;
+
import java.util.ArrayList;
import java.util.List;
-public class ListDataSource<T> extends TiledDataSource<T> {
+class ListDataSource<T> extends PositionalDataSource<T> {
private final List<T> mList;
public ListDataSource(List<T> list) {
@@ -27,13 +29,22 @@
}
@Override
- public int countItems() {
- return mList.size();
+ public void loadInitial(int requestedStartPosition, int requestedLoadSize, int pageSize,
+ @NonNull InitialLoadCallback<T> callback) {
+ final int totalCount = mList.size();
+
+ final int firstLoadPosition = computeFirstLoadPosition(
+ requestedStartPosition, requestedLoadSize, pageSize, totalCount);
+ final int firstLoadSize = Math.min(totalCount - firstLoadPosition, requestedLoadSize);
+
+ // for simplicity, we could return everything immediately,
+ // but we tile here since it's expected behavior
+ List<T> sublist = mList.subList(firstLoadPosition, firstLoadPosition + firstLoadSize);
+ callback.onResult(sublist, firstLoadPosition, totalCount);
}
@Override
- public List<T> loadRange(int startPosition, int count) {
- int endExclusive = Math.min(mList.size(), startPosition + count);
- return mList.subList(startPosition, endExclusive);
+ public void loadRange(int startPosition, int count, @NonNull LoadCallback<T> callback) {
+ callback.onResult(mList.subList(startPosition, startPosition + count));
}
}
diff --git a/paging/common/src/main/java/android/arch/paging/Page.java b/paging/common/src/main/java/android/arch/paging/Page.java
deleted file mode 100644
index e9890ed..0000000
--- a/paging/common/src/main/java/android/arch/paging/Page.java
+++ /dev/null
@@ -1,51 +0,0 @@
-/*
- * Copyright (C) 2017 The Android Open Source Project
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package android.arch.paging;
-
-import android.support.annotation.NonNull;
-import android.support.annotation.Nullable;
-
-import java.util.List;
-
-/**
- * Immutable class representing a page of data loaded from a DataSource.
- * <p>
- * Optionally stores before/after keys for cases where they cannot be computed, but the DataSource
- * can provide them as part of loading a page.
- * <p>
- * A page's list must never be modified.
- */
-class Page<K, V> {
- @SuppressWarnings("WeakerAccess")
- @Nullable
- public final K beforeKey;
- @NonNull
- public final List<V> items;
- @SuppressWarnings("WeakerAccess")
- @Nullable
- public K afterKey;
-
- Page(@NonNull List<V> items) {
- this(null, items, null);
- }
-
- Page(@Nullable K beforeKey, @NonNull List<V> items, @Nullable K afterKey) {
- this.beforeKey = beforeKey;
- this.items = items;
- this.afterKey = afterKey;
- }
-}
diff --git a/paging/common/src/main/java/android/arch/paging/PageResult.java b/paging/common/src/main/java/android/arch/paging/PageResult.java
index 55d5fb7..4384e72 100644
--- a/paging/common/src/main/java/android/arch/paging/PageResult.java
+++ b/paging/common/src/main/java/android/arch/paging/PageResult.java
@@ -16,11 +16,22 @@
package android.arch.paging;
-import android.support.annotation.AnyThread;
import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
-class PageResult<K, V> {
+import java.util.Collections;
+import java.util.List;
+
+class PageResult<T> {
+ @SuppressWarnings("unchecked")
+ private static final PageResult INVALID_RESULT =
+ new PageResult(Collections.EMPTY_LIST, 0);
+
+ @SuppressWarnings("unchecked")
+ static <T> PageResult<T> getInvalidResult() {
+ return INVALID_RESULT;
+ }
+
static final int INIT = 0;
// contiguous results
@@ -30,8 +41,8 @@
// non-contiguous, tile result
static final int TILE = 3;
- public final int type;
- public final Page<K, V> page;
+ @NonNull
+ public final List<T> page;
@SuppressWarnings("WeakerAccess")
public final int leadingNulls;
@SuppressWarnings("WeakerAccess")
@@ -39,26 +50,34 @@
@SuppressWarnings("WeakerAccess")
public final int positionOffset;
- PageResult(int type, Page<K, V> page, int leadingNulls, int trailingNulls, int positionOffset) {
- this.type = type;
- this.page = page;
+ PageResult(@NonNull List<T> list, int leadingNulls, int trailingNulls, int positionOffset) {
+ this.page = list;
this.leadingNulls = leadingNulls;
this.trailingNulls = trailingNulls;
this.positionOffset = positionOffset;
}
- PageResult(int type) {
- this.type = type;
- this.page = null;
+ PageResult(@NonNull List<T> list, int positionOffset) {
+ this.page = list;
this.leadingNulls = 0;
this.trailingNulls = 0;
- this.positionOffset = 0;
+ this.positionOffset = positionOffset;
}
- interface Receiver<K, V> {
- @AnyThread
- void postOnPageResult(@NonNull PageResult<K, V> pageResult);
+ @Override
+ public String toString() {
+ return "Result " + leadingNulls
+ + ", " + page
+ + ", " + trailingNulls
+ + ", offset " + positionOffset;
+ }
+
+ public boolean isInvalid() {
+ return this == INVALID_RESULT;
+ }
+
+ abstract static class Receiver<T> {
@MainThread
- void onPageResult(@NonNull PageResult<K, V> pageResult);
+ public abstract void onPageResult(int type, @NonNull PageResult<T> pageResult);
}
}
diff --git a/paging/common/src/main/java/android/arch/paging/PagedList.java b/paging/common/src/main/java/android/arch/paging/PagedList.java
index f18e108..275684f 100644
--- a/paging/common/src/main/java/android/arch/paging/PagedList.java
+++ b/paging/common/src/main/java/android/arch/paging/PagedList.java
@@ -17,6 +17,7 @@
package android.arch.paging;
import android.support.annotation.AnyThread;
+import android.support.annotation.MainThread;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.annotation.RestrictTo;
@@ -51,7 +52,7 @@
* PagedList can present data for an unbounded, infinite scrolling list, or a very large but
* countable list. Use {@link Config} to control how many items a PagedList loads, and when.
* <p>
- * If you use {@link LivePagedListProvider} to get a
+ * If you use {@link LivePagedListBuilder} to get a
* {@link android.arch.lifecycle.LiveData}<PagedList>, it will initialize PagedLists on a
* background thread for you.
* <h4>Placeholders</h4>
@@ -88,9 +89,8 @@
* </ul>
* <p>
* Placeholders are enabled by default, but can be disabled in two ways. They are disabled if the
- * DataSource returns {@link DataSource#COUNT_UNDEFINED} from any item counting method, or if
- * {@code false} is passed to {@link Config.Builder#setEnablePlaceholders(boolean)} when building a
- * {@link Config}.
+ * DataSource does not count its data set in its initial load, or if {@code false} is passed to
+ * {@link Config.Builder#setEnablePlaceholders(boolean)} when building a {@link Config}.
*
* @param <T> The type of the entries in the list.
*/
@@ -104,7 +104,7 @@
@NonNull
final Config mConfig;
@NonNull
- final PagedStorage<?, T> mStorage;
+ final PagedStorage<T> mStorage;
int mLastLoad = 0;
T mLastItem = null;
@@ -123,7 +123,7 @@
protected final ArrayList<WeakReference<Callback>> mCallbacks = new ArrayList<>();
- PagedList(@NonNull PagedStorage<?, T> storage,
+ PagedList(@NonNull PagedStorage<T> storage,
@NonNull Executor mainThreadExecutor,
@NonNull Executor backgroundThreadExecutor,
@Nullable BoundaryCallback<T> boundaryCallback,
@@ -162,7 +162,8 @@
if (dataSource.isContiguous() || !config.enablePlaceholders) {
if (!dataSource.isContiguous()) {
//noinspection unchecked
- dataSource = (DataSource<K, T>) ((TiledDataSource<T>) dataSource).getAsContiguous();
+ dataSource = (DataSource<K, T>) ((PositionalDataSource<T>) dataSource)
+ .wrapAsContiguousWithoutPlaceholders();
}
ContiguousDataSource<K, T> contigDataSource = (ContiguousDataSource<K, T>) dataSource;
return new ContiguousPagedList<>(contigDataSource,
@@ -172,7 +173,7 @@
config,
key);
} else {
- return new TiledPagedList<>((TiledDataSource<T>) dataSource,
+ return new TiledPagedList<>((PositionalDataSource<T>) dataSource,
mainThreadExecutor,
backgroundThreadExecutor,
boundaryCallback,
@@ -195,7 +196,7 @@
* Because PagedLists are initialized with data, PagedLists must be built on a background
* thread.
* <p>
- * {@link LivePagedListProvider} does this creation on a background thread automatically, if you
+ * {@link LivePagedListBuilder} does this creation on a background thread automatically, if you
* want to receive a {@code LiveData<PagedList<...>>}.
*
* @param <Key> Type of key used to load data from the DataSource.
@@ -211,9 +212,9 @@
private Key mInitialKey;
/**
- * The source of data that the PagedList should load from.
- * @param dataSource Source of data for the PagedList.
+ * The source of data that the PagedList will load from.
*
+ * @param dataSource Source of data for the PagedList.
* @return this
*/
@NonNull
@@ -286,8 +287,21 @@
/**
* Creates a {@link PagedList} with the given parameters.
* <p>
- * This call will initial data and perform any counting needed to initialize the PagedList,
- * therefore it should only be called on a worker thread.
+ * This call will dispatch the {@link DataSource}'s loadInitial method immediately. If a
+ * DataSource posts all of its work (e.g. to a network thread), the PagedList will
+ * be immediately created as empty, and grow to its initial size when the initial load
+ * completes.
+ * <p>
+ * If the DataSource implements its load synchronously, doing the load work immediately in
+ * the loadInitial method, the PagedList will block on that load before completing
+ * construction. In this case, use a background thread to create a PagedList.
+ * <p>
+ * It's fine to create a PagedList with an async DataSource on the main thread, such as in
+ * the constructor of a ViewModel. An async network load won't block the initialLoad
+ * function. For a synchronous DataSource such as one created from a Room database, a
+ * {@code LiveData<PagedList>} can be safely constructed with {@link LivePagedListBuilder}
+ * on the main thread, since actual construction work is deferred, and done on a background
+ * thread.
* <p>
* While build() will always return a PagedList, it's important to note that the PagedList
* initial load may fail to acquire data from the DataSource. This can happen for example if
@@ -451,13 +465,11 @@
// safe to deref mBoundaryCallback here, since we only defer if mBoundaryCallback present
if (begin) {
//noinspection ConstantConditions
- mBoundaryCallback.onItemAtFrontLoaded(
- snapshot(), mStorage.getFirstLoadedItem(), mStorage.size());
+ mBoundaryCallback.onItemAtFrontLoaded(mStorage.getFirstLoadedItem());
}
if (end) {
//noinspection ConstantConditions
- mBoundaryCallback.onItemAtEndLoaded(
- snapshot(), mStorage.getLastLoadedItem(), mStorage.size());
+ mBoundaryCallback.onItemAtEndLoaded(mStorage.getLastLoadedItem());
}
}
@@ -501,7 +513,6 @@
if (isImmutable()) {
return this;
}
-
return new SnapshotPagedList<>(this);
}
@@ -522,7 +533,7 @@
* <p>
* When a PagedList is invalidated, you can pass the key returned by this function to initialize
* the next PagedList. This ensures (depending on load times) that the next PagedList that
- * arrives will have data that overlaps. If you use {@link LivePagedListProvider}, it will do
+ * arrives will have data that overlaps. If you use {@link LivePagedListBuilder}, it will do
* this for you.
*
* @return Key of position most recently passed to {@link #loadAround(int)}.
@@ -556,8 +567,8 @@
/**
* Position offset of the data in the list.
* <p>
- * If data is supplied by a {@link TiledDataSource}, the item returned from <code>get(i)</code>
- * has a position of <code>i + getPositionOffset()</code>.
+ * If data is supplied by a {@link PositionalDataSource}, the item returned from
+ * <code>get(i)</code> has a position of <code>i + getPositionOffset()</code>.
* <p>
* If the DataSource is a {@link KeyedDataSource}, and thus doesn't use positions, returns 0.
*/
@@ -583,15 +594,25 @@
* GC'd.
*
* @param previousSnapshot Snapshot previously captured from this List, or null.
- * @param callback Callback to dispatch to.
+ * @param callback LoadCallback to dispatch to.
* @see #removeWeakCallback(Callback)
*/
@SuppressWarnings("WeakerAccess")
public void addWeakCallback(@Nullable List<T> previousSnapshot, @NonNull Callback callback) {
if (previousSnapshot != null && previousSnapshot != this) {
- PagedList<T> storageSnapshot = (PagedList<T>) previousSnapshot;
- //noinspection unchecked
- dispatchUpdatesSinceSnapshot(storageSnapshot, callback);
+
+ if (previousSnapshot.isEmpty()) {
+ if (!mStorage.isEmpty()) {
+ // If snapshot is empty, diff is trivial - just notify number new items.
+ // Note: occurs in async init, when snapshot taken before init page arrives
+ callback.onInserted(0, mStorage.size());
+ }
+ } else {
+ PagedList<T> storageSnapshot = (PagedList<T>) previousSnapshot;
+
+ //noinspection unchecked
+ dispatchUpdatesSinceSnapshot(storageSnapshot, callback);
+ }
}
// first, clean up any empty weak refs
@@ -608,7 +629,7 @@
/**
* Removes a previously added callback.
*
- * @param callback Callback, previously added.
+ * @param callback LoadCallback, previously added.
* @see #addWeakCallback(List, Callback)
*/
@SuppressWarnings("WeakerAccess")
@@ -645,6 +666,14 @@
}
}
+
+
+ /**
+ * Dispatch updates since the non-empty snapshot was taken.
+ *
+ * @param snapshot Non-empty snapshot.
+ * @param callback LoadCallback for updates that have occurred since snapshot.
+ */
abstract void dispatchUpdatesSinceSnapshot(@NonNull PagedList<T> snapshot,
@NonNull Callback callback);
@@ -826,13 +855,6 @@
* This value is typically larger than page size, so on first load data there's a large
* enough range of content loaded to cover small scrolls.
* <p>
- * If used with a {@link TiledDataSource}, this value is rounded to the nearest number
- * of pages, with a minimum of two pages, and loaded with a single call to
- * {@link TiledDataSource#loadRange(int, int)}.
- * <p>
- * If used with a {@link KeyedDataSource}, this value will be passed to
- * {@link KeyedDataSource#loadInitial(int)}.
- * <p>
* If not set, defaults to three times page size.
*
* @param initialLoadSizeHint Number of items to load while initializing the PagedList.
@@ -873,13 +895,43 @@
}
/**
- * WIP API for load-more-into-local-storage callbacks
+ * Signals when a PagedList has reached the end of available data.
+ * <p>
+ * This can be used to implement paging from the network into a local database - when the
+ * database has no more data to present, a BoundaryCallback can be used to fetch more data.
+ * <p>
+ * If an instance is shared across multiple PagedLists (e.g. when passed to
+ * {@link LivePagedListBuilder#setBoundaryCallback}), the callbacks may be issued multiple
+ * times. If for example {@link #onItemAtEndLoaded(Object)} triggers a network load, it should
+ * avoid triggering it again while the load is ongoing.
+ *
+ * @param <T> Type loaded by the PagedList.
*/
+ @MainThread
public abstract static class BoundaryCallback<T> {
+ /**
+ * Called when zero items are returned from an initial load of the PagedList's data source.
+ */
public abstract void onZeroItemsLoaded();
- public abstract void onItemAtFrontLoaded(@NonNull List<T> pagedListSnapshot,
- @NonNull T itemAtFront, int pagedListSize);
- public abstract void onItemAtEndLoaded(@NonNull List<T> pagedListSnapshot,
- @NonNull T itemAtEnd, int pagedListSize);
+
+ /**
+ * Called when the item at the front of the PagedList has been loaded, and access has
+ * occurred within {@link Config#prefetchDistance} of it.
+ * <p>
+ * No more data will be prepended to the PagedList before this item.
+ *
+ * @param itemAtFront The first item of PagedList
+ */
+ public abstract void onItemAtFrontLoaded(@NonNull T itemAtFront);
+
+ /**
+ * Called when the item at the end of the PagedList has been loaded, and access has
+ * occurred within {@link Config#prefetchDistance} of it.
+ * <p>
+ * No more data will be appended to the PagedList after this item.
+ *
+ * @param itemAtEnd The first item of PagedList
+ */
+ public abstract void onItemAtEndLoaded(@NonNull T itemAtEnd);
}
}
diff --git a/paging/common/src/main/java/android/arch/paging/PagedStorage.java b/paging/common/src/main/java/android/arch/paging/PagedStorage.java
index b857462..d4531d3 100644
--- a/paging/common/src/main/java/android/arch/paging/PagedStorage.java
+++ b/paging/common/src/main/java/android/arch/paging/PagedStorage.java
@@ -17,13 +17,21 @@
package android.arch.paging;
import android.support.annotation.NonNull;
+import android.support.annotation.Nullable;
import java.util.AbstractList;
import java.util.ArrayList;
-import java.util.Collections;
import java.util.List;
-final class PagedStorage<K, V> extends AbstractList<V> {
+final class PagedStorage<T> extends AbstractList<T> {
+ /**
+ * Lists instances are compared (with instance equality) to PLACEHOLDER_LIST to check if an item
+ * in that position is already loading. We use a singleton placeholder list that is distinct
+ * from Collections.EMPTY_LIST for safety.
+ */
+ @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
+ private static final List PLACEHOLDER_LIST = new ArrayList();
+
// Always set
private int mLeadingNullCount;
/**
@@ -37,7 +45,7 @@
* Non-contiguous - mPages may have nulls or a placeholder page, isTiled() always returns true.
* mPages may have nulls, or placeholder (empty) pages while content is loading.
*/
- private final ArrayList<Page<K, V>> mPages;
+ private final ArrayList<List<T>> mPages;
private int mTrailingNullCount;
private int mPositionOffset;
@@ -53,9 +61,6 @@
private int mNumberPrepended;
private int mNumberAppended;
- // only used in tiling case
- private Page<K, V> mPlaceholderPage;
-
PagedStorage() {
mLeadingNullCount = 0;
mPages = new ArrayList<>();
@@ -67,12 +72,12 @@
mNumberAppended = 0;
}
- PagedStorage(int leadingNulls, Page<K, V> page, int trailingNulls) {
+ PagedStorage(int leadingNulls, List<T> page, int trailingNulls) {
this();
init(leadingNulls, page, trailingNulls, 0);
}
- private PagedStorage(PagedStorage<K, V> other) {
+ private PagedStorage(PagedStorage<T> other) {
mLeadingNullCount = other.mLeadingNullCount;
mPages = new ArrayList<>(other.mPages);
mTrailingNullCount = other.mTrailingNullCount;
@@ -81,40 +86,37 @@
mPageSize = other.mPageSize;
mNumberPrepended = other.mNumberPrepended;
mNumberAppended = other.mNumberAppended;
-
- // preserve placeholder page so we can locate placeholder pages if needed later
- mPlaceholderPage = other.mPlaceholderPage;
}
- PagedStorage<K, V> snapshot() {
+ PagedStorage<T> snapshot() {
return new PagedStorage<>(this);
}
- private void init(int leadingNulls, Page<K, V> page, int trailingNulls, int positionOffset) {
+ private void init(int leadingNulls, List<T> page, int trailingNulls, int positionOffset) {
mLeadingNullCount = leadingNulls;
mPages.clear();
mPages.add(page);
mTrailingNullCount = trailingNulls;
mPositionOffset = positionOffset;
- mStorageCount = page.items.size();
+ mStorageCount = page.size();
// initialized as tiled. There may be 3 nulls, 2 items, but we still call this tiled
// even if it will break if nulls convert.
- mPageSize = page.items.size();
+ mPageSize = page.size();
mNumberPrepended = 0;
mNumberAppended = 0;
}
- void init(int leadingNulls, Page<K, V> page, int trailingNulls, int positionOffset,
+ void init(int leadingNulls, @NonNull List<T> page, int trailingNulls, int positionOffset,
@NonNull Callback callback) {
init(leadingNulls, page, trailingNulls, positionOffset);
callback.onInitialized(size());
}
@Override
- public V get(int i) {
+ public T get(int i) {
if (i < 0 || i >= size()) {
throw new IndexOutOfBoundsException("Index: " + i + ", Size: " + size());
}
@@ -138,7 +140,7 @@
pageInternalIndex = localIndex;
final int localPageCount = mPages.size();
for (localPageIndex = 0; localPageIndex < localPageCount; localPageIndex++) {
- int pageSize = mPages.get(localPageIndex).items.size();
+ int pageSize = mPages.get(localPageIndex).size();
if (pageSize > pageInternalIndex) {
// stop, found the page
break;
@@ -147,12 +149,12 @@
}
}
- Page<?, V> page = mPages.get(localPageIndex);
- if (page == null || page.items.size() == 0) {
+ List<T> page = mPages.get(localPageIndex);
+ if (page == null || page.size() == 0) {
// can only occur in tiled case, with untouched inner/placeholder pages
return null;
}
- return page.items.get(pageInternalIndex);
+ return page.get(pageInternalIndex);
}
/**
@@ -207,8 +209,8 @@
int total = mLeadingNullCount;
final int pageCount = mPages.size();
for (int i = 0; i < pageCount; i++) {
- Page page = mPages.get(i);
- if (page != null && page != mPlaceholderPage) {
+ List page = mPages.get(i);
+ if (page != null && page != PLACEHOLDER_LIST) {
break;
}
total += mPageSize;
@@ -219,8 +221,8 @@
int computeTrailingNulls() {
int total = mTrailingNullCount;
for (int i = mPages.size() - 1; i >= 0; i--) {
- Page page = mPages.get(i);
- if (page != null && page != mPlaceholderPage) {
+ List page = mPages.get(i);
+ if (page != null && page != PLACEHOLDER_LIST) {
break;
}
total += mPageSize;
@@ -230,21 +232,21 @@
// ---------------- Contiguous API -------------------
- V getFirstLoadedItem() {
+ T getFirstLoadedItem() {
// safe to access first page's first item here:
// If contiguous, mPages can't be empty, can't hold null Pages, and items can't be empty
- return mPages.get(0).items.get(0);
+ return mPages.get(0).get(0);
}
- V getLastLoadedItem() {
+ T getLastLoadedItem() {
// safe to access last page's last item here:
// If contiguous, mPages can't be empty, can't hold null Pages, and items can't be empty
- Page<K, V> page = mPages.get(mPages.size() - 1);
- return page.items.get(page.items.size() - 1);
+ List<T> page = mPages.get(mPages.size() - 1);
+ return page.get(page.size() - 1);
}
- public void prependPage(@NonNull Page<K, V> page, @NonNull Callback callback) {
- final int count = page.items.size();
+ void prependPage(@NonNull List<T> page, @NonNull Callback callback) {
+ final int count = page.size();
if (count == 0) {
// Nothing returned from source, stop loading in this direction
return;
@@ -274,8 +276,8 @@
callback.onPagePrepended(mLeadingNullCount, changedCount, addedCount);
}
- public void appendPage(@NonNull Page<K, V> page, @NonNull Callback callback) {
- final int count = page.items.size();
+ void appendPage(@NonNull List<T> page, @NonNull Callback callback) {
+ final int count = page.size();
if (count == 0) {
// Nothing returned from source, stop loading in this direction
return;
@@ -284,7 +286,7 @@
if (mPageSize > 0) {
// if the previous page was smaller than mPageSize,
// or if this page is larger than the previous, disable tiling
- if (mPages.get(mPages.size() - 1).items.size() != mPageSize
+ if (mPages.get(mPages.size() - 1).size() != mPageSize
|| count > mPageSize) {
mPageSize = -1;
}
@@ -306,8 +308,30 @@
// ------------------ Non-Contiguous API (tiling required) ----------------------
- public void insertPage(int position, @NonNull Page<K, V> page, Callback callback) {
- final int newPageSize = page.items.size();
+ void initAndSplit(int leadingNulls, @NonNull List<T> multiPageList,
+ int trailingNulls, int positionOffset, int pageSize, @NonNull Callback callback) {
+
+ int pageCount = (multiPageList.size() + (pageSize - 1)) / pageSize;
+ for (int i = 0; i < pageCount; i++) {
+ int beginInclusive = i * pageSize;
+ int endExclusive = Math.min(multiPageList.size(), (i + 1) * pageSize);
+
+ List<T> sublist = multiPageList.subList(beginInclusive, endExclusive);
+
+ if (i == 0) {
+ // Trailing nulls for first page includes other pages in multiPageList
+ int initialTrailingNulls = trailingNulls + multiPageList.size() - sublist.size();
+ init(leadingNulls, sublist, initialTrailingNulls, positionOffset);
+ } else {
+ int insertPosition = leadingNulls + beginInclusive;
+ insertPage(insertPosition, sublist, null);
+ }
+ }
+ callback.onInitialized(size());
+ }
+
+ public void insertPage(int position, @NonNull List<T> page, @Nullable Callback callback) {
+ final int newPageSize = page.size();
if (newPageSize != mPageSize) {
// differing page size is OK in 2 cases, when the page is being added:
// 1) to the end (in which case, ignore new smaller size)
@@ -334,22 +358,15 @@
int localPageIndex = pageIndex - mLeadingNullCount / mPageSize;
- Page<K, V> oldPage = mPages.get(localPageIndex);
- if (oldPage != null && oldPage != mPlaceholderPage) {
+ List<T> oldPage = mPages.get(localPageIndex);
+ if (oldPage != null && oldPage != PLACEHOLDER_LIST) {
throw new IllegalArgumentException(
"Invalid position " + position + ": data already loaded");
}
mPages.set(localPageIndex, page);
- callback.onPageInserted(position, page.items.size());
- }
-
- private Page<K, V> getPlaceholderPage() {
- if (mPlaceholderPage == null) {
- @SuppressWarnings("unchecked")
- List<V> list = Collections.emptyList();
- mPlaceholderPage = new Page<>(null, list, null);
+ if (callback != null) {
+ callback.onPageInserted(position, page.size());
}
- return mPlaceholderPage;
}
private void allocatePageRange(final int minimumPage, final int maximumPage) {
@@ -399,7 +416,8 @@
for (int pageIndex = minimumPage; pageIndex <= maximumPage; pageIndex++) {
int localPageIndex = pageIndex - leadingNullPages;
if (mPages.get(localPageIndex) == null) {
- mPages.set(localPageIndex, getPlaceholderPage());
+ //noinspection unchecked
+ mPages.set(localPageIndex, PLACEHOLDER_LIST);
callback.onPagePlaceholderInserted(pageIndex);
}
}
@@ -414,9 +432,9 @@
return false;
}
- Page<K, V> page = mPages.get(index - leadingNullPages);
+ List<T> page = mPages.get(index - leadingNullPages);
- return page != null && page != mPlaceholderPage;
+ return page != null && page != PLACEHOLDER_LIST;
}
@Override
diff --git a/paging/common/src/main/java/android/arch/paging/PositionalDataSource.java b/paging/common/src/main/java/android/arch/paging/PositionalDataSource.java
index fa2932a..5dd3a83 100644
--- a/paging/common/src/main/java/android/arch/paging/PositionalDataSource.java
+++ b/paging/common/src/main/java/android/arch/paging/PositionalDataSource.java
@@ -1,5 +1,5 @@
/*
- * Copyright (C) 2017 The Android Open Source Project
+ * Copyright 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
@@ -20,115 +20,139 @@
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
-import java.util.List;
+import java.util.Collections;
/**
- * Incremental data loader for paging positional content, where content can be loaded based on its
- * integer position.
+ * Position-based data loader for a fixed-size, countable data set, supporting loads at arbitrary
+ * positions.
* <p>
- * Use PositionalDataSource if you only need position as input for item loading - if for example,
- * you're asking the backend for items at positions 10 through 20, or using a limit/offset database
- * query to load items at query position 10 through 20.
+ * Extend PositionalDataSource if you can support counting your data set, and loading based on
+ * position information.
* <p>
- * Implement a DataSource using PositionalDataSource if position is the only information you need to
- * load items.
+ * Note that unless {@link PagedList.Config#enablePlaceholders placeholders are disabled}
+ * PositionalDataSource requires counting the size of the dataset. This allows pages to be tiled in
+ * at arbitrary, non-contiguous locations based upon what the user observes in a {@link PagedList}.
* <p>
- * Note that {@link BoundedDataSource} provides a simpler API for positional loading, if your
- * backend or data store doesn't require
- * <p>
- * @param <Value> Value type of items being loaded by the DataSource.
+ * Room can generate a Factory of PositionalDataSources for you:
+ * <pre>
+ * {@literal @}Dao
+ * interface UserDao {
+ * {@literal @}Query("SELECT * FROM user ORDER BY mAge DESC")
+ * public abstract DataSource.Factory<Integer, User> loadUsersByAgeDesc();
+ * }</pre>
+ *
+ * @param <T> Type of items being loaded by the PositionalDataSource.
*/
-abstract class PositionalDataSource<Value> extends ContiguousDataSource<Integer, Value> {
+public abstract class PositionalDataSource<T> extends DataSource<Integer, T> {
/**
- * Number of items that this DataSource can provide in total, or COUNT_UNDEFINED.
- *
- * @return number of items that this DataSource can provide in total, or COUNT_UNDEFINED
- * if difficult or undesired to compute.
- */
- public int countItems() {
- return COUNT_UNDEFINED;
- }
-
- @Nullable
- @Override
- List<Value> loadAfterImpl(int currentEndIndex, @NonNull Value currentEndItem, int pageSize) {
- return loadAfter(currentEndIndex + 1, pageSize);
- }
-
- @Nullable
- @Override
- List<Value> loadBeforeImpl(int currentBeginIndex, @NonNull Value currentBeginItem,
- int pageSize) {
- return loadBefore(currentBeginIndex - 1, pageSize);
- }
-
- @Override
- void loadInitial(Integer position, int initialLoadSize, boolean enablePlaceholders,
- @NonNull PageResult.Receiver<Integer, Value> receiver) {
-
- final int convertPosition = position == null ? 0 : position;
- final int loadPosition = Math.max(0, (convertPosition - initialLoadSize / 2));
-
- int count = COUNT_UNDEFINED;
- if (enablePlaceholders) {
- count = countItems();
- }
- List<Value> data = loadAfter(loadPosition, initialLoadSize);
-
- if (data == null) {
- receiver.onPageResult(new PageResult<Integer, Value>(PageResult.INIT));
- return;
- }
-
- final boolean uncounted = count == COUNT_UNDEFINED;
- int leadingNullCount = uncounted ? 0 : loadPosition;
- int trailingNullCount = uncounted ? 0 : count - leadingNullCount - data.size();
- int positionOffset = uncounted ? loadPosition : 0;
-
- receiver.onPageResult(new PageResult<>(
- PageResult.INIT,
- new Page<Integer, Value>(data),
- leadingNullCount,
- trailingNullCount,
- positionOffset));
- }
-
- /**
- * Load data after currently loaded content, starting at the provided index.
+ * Load initial list data.
* <p>
- * 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.
+ * This method is called to load the initial page(s) from the DataSource.
+ * <p>
+ * Result list must be a multiple of pageSize to enable efficient tiling.
*
- * @param startIndex Load items starting at this index.
- * @param pageSize Suggested number of items to load.
- * @return List of items, starting at position currentEndIndex + 1. Null if the data source is
- * no longer valid, and should not be queried again.
+ * @param requestedStartPosition Initial load position requested. Note that this may not be
+ * within the bounds of your data set, it should be corrected
+ * before you make your query.
+ * @param requestedLoadSize Requested number of items to load. Note that this may be larger than
+ * available data.
+ * @param pageSize Defines page size acceptable for return values. List of items passed to the
+ * callback must be an integer multiple of page size.
+ * @param callback DataSource.InitialLoadCallback that receives initial load data, including
+ * position and total data set size.
*/
@WorkerThread
- @Nullable
- public abstract List<Value> loadAfter(int startIndex, int pageSize);
+ public abstract void loadInitial(int requestedStartPosition, int requestedLoadSize,
+ int pageSize, @NonNull InitialLoadCallback<T> callback);
/**
- * Load data before the currently loaded content, starting at the provided index.
+ * Called to load a range of data from the DataSource.
* <p>
- * 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.
+ * This method is called to load additional pages from the DataSource after the
+ * InitialLoadCallback passed to loadInitial has initialized a PagedList.
+ * <p>
+ * Unlike {@link #loadInitial(int, int, int, InitialLoadCallback)}, this method must return the
+ * number of items requested, at the position requested.
*
- * @param startIndex Load items, starting at this index.
- * @param pageSize Suggested number of items to load.
- * @return List of items, in descending order, starting at position currentBeginIndex - 1. Null
- * if the data source is no longer valid, and should not be queried again.
+ * @param startPosition Initial load position.
+ * @param count Number of items to load.
+ * @param callback DataSource.LoadCallback that receives loaded data.
*/
@WorkerThread
- @Nullable
- public abstract List<Value> loadBefore(int startIndex, int pageSize);
+ public abstract void loadRange(int startPosition, int count,
+ @NonNull LoadCallback<T> callback);
@Override
- Integer getKey(int position, Value item) {
- if (position < 0) {
- return null;
+ boolean isContiguous() {
+ return false;
+ }
+
+ @NonNull
+ ContiguousDataSource<Integer, T> wrapAsContiguousWithoutPlaceholders() {
+ return new ContiguousWithoutPlaceholdersWrapper<>(this);
+ }
+
+ static int computeFirstLoadPosition(int position, int firstLoadSize, int pageSize, int size) {
+ int roundedPageStart = Math.round(position / pageSize) * pageSize;
+
+ // maximum start pos is that which will encompass end of list
+ int maximumLoadPage = ((size - firstLoadSize + pageSize - 1) / pageSize) * pageSize;
+ roundedPageStart = Math.min(maximumLoadPage, roundedPageStart);
+
+ // minimum start position is 0
+ roundedPageStart = Math.max(0, roundedPageStart);
+
+ return roundedPageStart;
+ }
+
+ @SuppressWarnings("deprecation")
+ static class ContiguousWithoutPlaceholdersWrapper<Value>
+ extends ContiguousDataSource<Integer, Value> {
+
+ @NonNull
+ final PositionalDataSource<Value> mPositionalDataSource;
+
+ ContiguousWithoutPlaceholdersWrapper(
+ @NonNull PositionalDataSource<Value> positionalDataSource) {
+ mPositionalDataSource = positionalDataSource;
}
- return position;
+
+ @Override
+ public void loadInitial(@Nullable Integer position, int initialLoadSize,
+ boolean enablePlaceholders, @NonNull InitialLoadCallback<Value> callback) {
+ final int convertPosition = position == null ? 0 : position;
+
+ // Note enablePlaceholders will be false here, but we don't have a way to communicate
+ // this to PositionalDataSource. This is fine, because only the list and its position
+ // offset will be consumed by the InitialLoadCallback.
+ mPositionalDataSource.loadInitial(
+ convertPosition, initialLoadSize, initialLoadSize, callback);
+ }
+
+ @Override
+ void loadAfter(int currentEndIndex, @NonNull Value currentEndItem, int pageSize,
+ @NonNull LoadCallback<Value> callback) {
+ int startIndex = currentEndIndex + 1;
+ mPositionalDataSource.loadRange(startIndex, pageSize, callback);
+ }
+
+ @Override
+ void loadBefore(int currentBeginIndex, @NonNull Value currentBeginItem, int pageSize,
+ @NonNull LoadCallback<Value> callback) {
+ int startIndex = currentBeginIndex - 1;
+ if (startIndex < 0) {
+ callback.onResult(Collections.<Value>emptyList());
+ } else {
+ int loadSize = Math.min(pageSize, startIndex + 1);
+ startIndex = startIndex - loadSize + 1;
+ mPositionalDataSource.loadRange(startIndex, loadSize, callback);
+ }
+ }
+
+ @Override
+ Integer getKey(int position, Value item) {
+ return position;
+ }
}
}
diff --git a/paging/common/src/main/java/android/arch/paging/TiledDataSource.java b/paging/common/src/main/java/android/arch/paging/TiledDataSource.java
index 0ea9428..27aeda0 100644
--- a/paging/common/src/main/java/android/arch/paging/TiledDataSource.java
+++ b/paging/common/src/main/java/android/arch/paging/TiledDataSource.java
@@ -16,84 +16,24 @@
package android.arch.paging;
-import android.support.annotation.Nullable;
+import android.support.annotation.NonNull;
+import android.support.annotation.RestrictTo;
import android.support.annotation.WorkerThread;
import java.util.Collections;
import java.util.List;
/**
- * Position-based data loader for fixed size, arbitrary positioned loading.
- * <p>
- * Extend TiledDataSource if you want to load arbitrary pages based solely on position information,
- * and can generate pages of a provided fixed size.
- * <p>
- * Room can generate a TiledDataSource for you:
- * <pre>
- * {@literal @}Dao
- * interface UserDao {
- * {@literal @}Query("SELECT * FROM user ORDER BY mAge DESC")
- * public abstract TiledDataSource<User> loadUsersByAgeDesc();
- * }</pre>
+ * @param <T> Type loaded by the TiledDataSource.
*
- * Under the hood, Room will generate code equivalent to the below, using a limit/offset SQL query:
- * <pre>
- * {@literal @}Dao
- * interface UserDao {
- * {@literal @}Query("SELECT COUNT(*) from user")
- * public abstract Integer getUserCount();
- *
- * {@literal @}Query("SELECT * from user ORDER BY mName DESC LIMIT :limit OFFSET :offset")
- * public abstract List<User> userNameLimitOffset(int limit, int offset);
- * }
- *
- * public class OffsetUserQueryDataSource extends TiledDataSource<User> {
- * private MyDatabase mDb;
- * private final UserDao mUserDao;
- * {@literal @}SuppressWarnings("FieldCanBeLocal")
- * private final InvalidationTracker.Observer mObserver;
- *
- * public OffsetUserQueryDataSource(MyDatabase db) {
- * mDb = db;
- * mUserDao = db.getUserDao();
- * mObserver = new InvalidationTracker.Observer("user") {
- * {@literal @}Override
- * public void onInvalidated({@literal @}NonNull Set<String> tables) {
- * // the user table has been invalidated, invalidate the DataSource
- * invalidate();
- * }
- * };
- * db.getInvalidationTracker().addWeakObserver(mObserver);
- * }
- *
- * {@literal @}Override
- * public boolean isInvalid() {
- * mDb.getInvalidationTracker().refreshVersionsSync();
- * return super.isInvalid();
- * }
- *
- * {@literal @}Override
- * public int countItems() {
- * return mUserDao.getUserCount();
- * }
- *
- * {@literal @}Override
- * public List<User> loadRange(int startPosition, int loadCount) {
- * return mUserDao.userNameLimitOffset(loadCount, startPosition);
- * }
- * }</pre>
- *
- * @param <Type> Type of items being loaded by the TiledDataSource.
+ * @deprecated Use {@link PositionalDataSource}
+ * @hide
*/
-public abstract class TiledDataSource<Type> extends DataSource<Integer, Type> {
+@SuppressWarnings("DeprecatedIsStillUsed")
+@Deprecated
+@RestrictTo(RestrictTo.Scope.LIBRARY_GROUP)
+public abstract class TiledDataSource<T> extends PositionalDataSource<T> {
- private int mItemCount;
-
- /**
- * Number of items that this DataSource can provide in total.
- *
- * @return Number of items this DataSource can provide. Must be <code>0</code> or greater.
- */
@WorkerThread
public abstract int countItems();
@@ -102,111 +42,39 @@
return false;
}
- /**
- * Called to load items at from the specified position range.
- * <p>
- * This method must return a list of requested size, unless at the end of list. Fixed size pages
- * enable TiledDataSource to navigate tiles efficiently, and quickly accesss any position in the
- * data set.
- * <p>
- * If a list of a different size is returned, but it is not the last list in the data set based
- * on the return value from {@link #countItems()}, an exception will be thrown.
- *
- * @param startPosition Index of first item to load.
- * @param count Number of items to load.
- * @return List of loaded items, of the requested length unless at end of list. Null if the
- * DataSource is no longer valid, and should not be queried again.
- */
@WorkerThread
- public abstract List<Type> loadRange(int startPosition, int count);
+ public abstract List<T> loadRange(int startPosition, int count);
- /**
- * blocking, and splits pages
- */
- void loadRangeInitial(int startPosition, int count, int pageSize, int itemCount,
- PageResult.Receiver<Integer, Type> receiver) {
- mItemCount = itemCount;
-
- if (itemCount == 0) {
- // no data to load, just immediately return empty
- receiver.onPageResult(new PageResult<>(
- PageResult.INIT, new Page<Integer, Type>(Collections.<Type>emptyList()),
- 0, 0, startPosition));
+ @Override
+ public void loadInitial(int requestedStartPosition, int requestedLoadSize, int pageSize,
+ @NonNull InitialLoadCallback<T> callback) {
+ int totalCount = countItems();
+ if (totalCount == 0) {
+ callback.onResult(Collections.<T>emptyList());
return;
}
- List<Type> list = loadRangeWrapper(startPosition, count);
+ // bound the size requested, based on known count
+ final int firstLoadPosition = computeFirstLoadPosition(
+ requestedStartPosition, requestedLoadSize, pageSize, totalCount);
+ final int firstLoadSize = Math.min(totalCount - firstLoadPosition, requestedLoadSize);
- count = Math.min(count, itemCount - startPosition);
-
- if (list == null) {
- // invalid data, pass to receiver
- receiver.onPageResult(new PageResult<Integer, Type>(
- PageResult.INIT, null, 0, 0, startPosition));
- return;
- }
-
- if (list.size() != count) {
- throw new IllegalStateException("Invalid list, requested size: " + count
- + ", returned size: " + list.size());
- }
-
- // emit the results as multiple pages
- int pageCount = (count + (pageSize - 1)) / pageSize;
- for (int i = 0; i < pageCount; i++) {
- int beginInclusive = i * pageSize;
- int endExclusive = Math.min(count, (i + 1) * pageSize);
-
- Page<Integer, Type> page = new Page<>(list.subList(beginInclusive, endExclusive));
-
- int leadingNulls = startPosition + beginInclusive;
- int trailingNulls = itemCount - leadingNulls - page.items.size();
- receiver.onPageResult(new PageResult<>(
- PageResult.INIT, page, leadingNulls, trailingNulls, 0));
- }
- }
-
- void loadRange(int startPosition, int count, PageResult.Receiver<Integer, Type> receiver) {
- List<Type> list = loadRangeWrapper(startPosition, count);
-
- Page<Integer, Type> page = null;
- int trailingNulls = mItemCount - startPosition;
-
+ // convert from legacy behavior
+ List<T> list = loadRange(firstLoadPosition, firstLoadSize);
if (list != null) {
- page = new Page<Integer, Type>(list);
- trailingNulls -= list.size();
+ callback.onResult(list, firstLoadPosition, totalCount);
+ } else {
+ invalidate();
}
- receiver.postOnPageResult(new PageResult<>(
- PageResult.TILE, page, startPosition, trailingNulls, 0));
}
- private List<Type> loadRangeWrapper(int startPosition, int count) {
- if (isInvalid()) {
- return null;
- }
- List<Type> list = loadRange(startPosition, count);
- if (isInvalid()) {
- return null;
- }
- return list;
- }
-
- ContiguousDataSource<Integer, Type> getAsContiguous() {
- return new TiledAsBoundedDataSource<>(this);
- }
-
- static class TiledAsBoundedDataSource<Value> extends BoundedDataSource<Value> {
- final TiledDataSource<Value> mTiledDataSource;
-
- TiledAsBoundedDataSource(TiledDataSource<Value> tiledDataSource) {
- mTiledDataSource = tiledDataSource;
- }
-
- @WorkerThread
- @Nullable
- @Override
- public List<Value> loadRange(int startPosition, int loadCount) {
- return mTiledDataSource.loadRange(startPosition, loadCount);
+ @Override
+ public void loadRange(int startPosition, int count, @NonNull LoadCallback<T> callback) {
+ List<T> list = loadRange(startPosition, count);
+ if (list != null) {
+ callback.onResult(list);
+ } else {
+ invalidate();
}
}
}
diff --git a/paging/common/src/main/java/android/arch/paging/TiledPagedList.java b/paging/common/src/main/java/android/arch/paging/TiledPagedList.java
index 76bb682..338d43c 100644
--- a/paging/common/src/main/java/android/arch/paging/TiledPagedList.java
+++ b/paging/common/src/main/java/android/arch/paging/TiledPagedList.java
@@ -25,32 +25,15 @@
class TiledPagedList<T> extends PagedList<T>
implements PagedStorage.Callback {
+ private final PositionalDataSource<T> mDataSource;
- private final TiledDataSource<T> mDataSource;
-
- @SuppressWarnings("unchecked")
- private final PagedStorage<Integer, T> mKeyedStorage = (PagedStorage<Integer, T>) mStorage;
-
- private final PageResult.Receiver<Integer, T> mReceiver =
- new PageResult.Receiver<Integer, T>() {
- @AnyThread
- @Override
- public void postOnPageResult(@NonNull final PageResult<Integer, T> pageResult) {
- // NOTE: if we're already on main thread, this can delay page receive by a frame
- mMainThreadExecutor.execute(new Runnable() {
- @Override
- public void run() {
- onPageResult(pageResult);
- }
- });
- }
-
+ private PageResult.Receiver<T> mReceiver = new PageResult.Receiver<T>() {
// Creation thread for initial synchronous load, otherwise main thread
// Safe to access main thread only state - no other thread has reference during construction
@AnyThread
@Override
- public void onPageResult(@NonNull PageResult<Integer, T> pageResult) {
- if (pageResult.page == null) {
+ public void onPageResult(int type, @NonNull PageResult<T> pageResult) {
+ if (pageResult.isInvalid()) {
detach();
return;
}
@@ -61,60 +44,62 @@
}
if (mStorage.getPageCount() == 0) {
- mKeyedStorage.init(
+ mStorage.initAndSplit(
pageResult.leadingNulls, pageResult.page, pageResult.trailingNulls,
- pageResult.positionOffset, TiledPagedList.this);
+ pageResult.positionOffset, mConfig.pageSize, TiledPagedList.this);
} else {
- mKeyedStorage.insertPage(pageResult.leadingNulls, pageResult.page,
+ mStorage.insertPage(pageResult.positionOffset, pageResult.page,
TiledPagedList.this);
}
if (mBoundaryCallback != null) {
boolean deferEmpty = mStorage.size() == 0;
- boolean deferBegin = !deferEmpty && pageResult.leadingNulls == 0;
- boolean deferEnd = !deferEmpty && pageResult.trailingNulls == 0;
+ boolean deferBegin = !deferEmpty
+ && pageResult.leadingNulls == 0
+ && pageResult.positionOffset == 0;
+ int size = size();
+ boolean deferEnd = !deferEmpty
+ && ((type == PageResult.INIT && pageResult.trailingNulls == 0)
+ || (type == PageResult.TILE
+ && pageResult.positionOffset
+ == (size - size % mConfig.pageSize)));
deferBoundaryCallbacks(deferEmpty, deferBegin, deferEnd);
}
}
};
@WorkerThread
- TiledPagedList(@NonNull TiledDataSource<T> dataSource,
+ TiledPagedList(@NonNull PositionalDataSource<T> dataSource,
@NonNull Executor mainThreadExecutor,
@NonNull Executor backgroundThreadExecutor,
@Nullable BoundaryCallback<T> boundaryCallback,
@NonNull Config config,
int position) {
- super(new PagedStorage<Integer, T>(), mainThreadExecutor, backgroundThreadExecutor,
+ super(new PagedStorage<T>(), mainThreadExecutor, backgroundThreadExecutor,
boundaryCallback, config);
mDataSource = dataSource;
final int pageSize = mConfig.pageSize;
+ mLastLoad = position;
- final int itemCount = mDataSource.countItems();
+ if (mDataSource.isInvalid()) {
+ detach();
+ } else {
+ final int firstLoadSize =
+ (Math.max(Math.round(mConfig.initialLoadSizeHint / pageSize), 2)) * pageSize;
- final int firstLoadSize = Math.min(itemCount,
- (Math.max(mConfig.initialLoadSizeHint / pageSize, 2)) * pageSize);
- final int firstLoadPosition = computeFirstLoadPosition(
- position, firstLoadSize, pageSize, itemCount);
+ final int idealStart = position - firstLoadSize / 2;
+ final int roundedPageStart = Math.max(0, Math.round(idealStart / pageSize) * pageSize);
- mDataSource.loadRangeInitial(firstLoadPosition, firstLoadSize, pageSize,
- itemCount, mReceiver);
- }
+ DataSource.InitialLoadCallback<T> callback =
+ new DataSource.InitialLoadCallback<>(true, mDataSource, mReceiver);
+ mDataSource.loadInitial(roundedPageStart, firstLoadSize, pageSize, callback);
- static int computeFirstLoadPosition(int position, int firstLoadSize, int pageSize, int size) {
- int idealStart = position - firstLoadSize / 2;
-
- int roundedPageStart = Math.round(idealStart / pageSize) * pageSize;
-
- // minimum start position is 0
- roundedPageStart = Math.max(0, roundedPageStart);
-
- // maximum start pos is that which will encompass end of list
- int maximumLoadPage = ((size - firstLoadSize + pageSize - 1) / pageSize) * pageSize;
- roundedPageStart = Math.min(maximumLoadPage, roundedPageStart);
-
- return roundedPageStart;
+ // If initialLoad's callback is not called within the body, we force any following calls
+ // to post to the UI thread. This constructor may be run on a background thread, but
+ // after constructor, mutation must happen on UI thread.
+ callback.setPostExecutor(mMainThreadExecutor);
+ }
}
@Override
@@ -132,7 +117,13 @@
protected void dispatchUpdatesSinceSnapshot(@NonNull PagedList<T> pagedListSnapshot,
@NonNull Callback callback) {
//noinspection UnnecessaryLocalVariable
- final PagedStorage<?, T> snapshot = pagedListSnapshot.mStorage;
+ final PagedStorage<T> snapshot = pagedListSnapshot.mStorage;
+
+ if (snapshot.isEmpty()
+ || mStorage.size() != snapshot.size()) {
+ throw new IllegalArgumentException("Invalid snapshot provided - doesn't appear"
+ + " to be a snapshot of this PagedList");
+ }
// loop through each page and signal the callback for any pages that are present now,
// but not in the snapshot.
@@ -186,7 +177,17 @@
return;
}
final int pageSize = mConfig.pageSize;
- mDataSource.loadRange(pageIndex * pageSize, pageSize, mReceiver);
+
+ if (mDataSource.isInvalid()) {
+ detach();
+ } else {
+ int startPosition = pageIndex * pageSize;
+ int count = Math.min(pageSize, mStorage.size() - startPosition);
+ DataSource.LoadCallback<T> callback = new DataSource.LoadCallback<>(
+ PageResult.TILE, mMainThreadExecutor, mDataSource, mReceiver);
+ callback.setPositionOffset(startPosition);
+ mDataSource.loadRange(startPosition, count, callback);
+ }
}
});
}
diff --git a/paging/common/src/test/java/android/arch/paging/AsyncListDataSource.kt b/paging/common/src/test/java/android/arch/paging/AsyncListDataSource.kt
new file mode 100644
index 0000000..48d6e29
--- /dev/null
+++ b/paging/common/src/test/java/android/arch/paging/AsyncListDataSource.kt
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.arch.paging
+
+class AsyncListDataSource<T>(list: List<T>)
+ : PositionalDataSource<T>() {
+ val workItems: MutableList<() -> Unit> = ArrayList()
+ private val listDataSource = ListDataSource(list)
+
+ override fun loadInitial(requestedStartPosition: Int, requestedLoadSize: Int, pageSize: Int,
+ callback: InitialLoadCallback<T>) {
+ workItems.add {
+ listDataSource.loadInitial(requestedStartPosition, requestedLoadSize, pageSize, callback)
+ }
+ }
+
+ override fun loadRange(startPosition: Int, count: Int, callback: LoadCallback<T>) {
+ workItems.add {
+ listDataSource.loadRange(startPosition, count, callback)
+ }
+ }
+
+ fun flush() {
+ workItems.map { it() }
+ workItems.clear()
+ }
+}
diff --git a/paging/common/src/test/java/android/arch/paging/ContiguousPagedListTest.kt b/paging/common/src/test/java/android/arch/paging/ContiguousPagedListTest.kt
index 7331bfe..5ae0f9f 100644
--- a/paging/common/src/test/java/android/arch/paging/ContiguousPagedListTest.kt
+++ b/paging/common/src/test/java/android/arch/paging/ContiguousPagedListTest.kt
@@ -18,17 +18,16 @@
import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
+import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.Parameterized
-import org.mockito.ArgumentCaptor
-import org.mockito.Mockito.any
-import org.mockito.Mockito.eq
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyNoMoreInteractions
import org.mockito.Mockito.verifyZeroInteractions
-import java.util.Collections
+
@RunWith(Parameterized::class)
class ContiguousPagedListTest(private val mCounted: Boolean) {
@@ -44,33 +43,46 @@
}
private inner class TestSource(val listData: List<Item> = ITEMS)
- : PositionalDataSource<Item>() {
- override fun countItems(): Int {
- return if (mCounted) {
- listData.size
+ : ContiguousDataSource<Int, Item>() {
+ override fun loadInitial(key: Int?, initialLoadSize: Int,
+ enablePlaceholders: Boolean, callback: InitialLoadCallback<Item>) {
+
+ val convertPosition = key ?: 0
+ val loadPosition = Math.max(0, (convertPosition - initialLoadSize / 2))
+
+ val data = getClampedRange(loadPosition, loadPosition + initialLoadSize)
+
+
+ if (enablePlaceholders && mCounted) {
+ callback.onResult(data, loadPosition, listData.size)
} else {
- DataSource.COUNT_UNDEFINED
+ // still must pass offset, even if not counted
+ callback.onResult(data, loadPosition)
}
}
- private fun getClampedRange(startInc: Int, endExc: Int, reverse: Boolean): List<Item> {
- val list = listData.subList(Math.max(0, startInc), Math.min(listData.size, endExc))
- if (reverse) {
- Collections.reverse(list)
- }
- return list
+ override fun loadAfter(currentEndIndex: Int, currentEndItem: Item, pageSize: Int,
+ callback: LoadCallback<Item>) {
+ val startIndex = currentEndIndex + 1
+ callback.onResult(getClampedRange(startIndex, startIndex + pageSize))
}
- override fun loadAfter(startIndex: Int, pageSize: Int): List<Item>? {
- return getClampedRange(startIndex, startIndex + pageSize, false)
+ override fun loadBefore(currentBeginIndex: Int, currentBeginItem: Item, pageSize: Int,
+ callback: LoadCallback<Item>) {
+ val startIndex = currentBeginIndex - 1
+ callback.onResult(getClampedRange(startIndex - pageSize + 1, startIndex + 1))
}
- override fun loadBefore(startIndex: Int, pageSize: Int): List<Item>? {
- return getClampedRange(startIndex - pageSize + 1, startIndex + 1, true)
+ override fun getKey(position: Int, item: Item?): Int {
+ return 0
+ }
+
+ private fun getClampedRange(startInc: Int, endExc: Int): List<Item> {
+ return listData.subList(Math.max(0, startInc), Math.min(listData.size, endExc))
}
}
- private fun verifyRange(start: Int, count: Int, actual: PagedStorage<*, Item>) {
+ private fun verifyRange(start: Int, count: Int, actual: PagedStorage<Item>) {
if (mCounted) {
// assert nulls + content
val expected = arrayOfNulls<Item>(ITEMS.size)
@@ -98,41 +110,6 @@
verifyRange(start, count, actual.mStorage)
}
- private fun verifyRange(start: Int, count: Int, actual: PageResult<Int, Item>) {
- if (mCounted) {
- assertEquals(start, actual.leadingNulls)
- assertEquals(ITEMS.size - start - count, actual.trailingNulls)
- assertEquals(0, actual.positionOffset)
- } else {
- assertEquals(0, actual.leadingNulls)
- assertEquals(0, actual.trailingNulls)
- assertEquals(start, actual.positionOffset)
- }
- assertEquals(ITEMS.subList(start, start + count), actual.page.items)
- }
-
- private fun verifyInitialLoad(start: Int, count : Int, initialPosition: Int, initialLoadSize: Int) {
- @Suppress("UNCHECKED_CAST")
- val receiver = mock(PageResult.Receiver::class.java) as PageResult.Receiver<Int, Item>
-
- @Suppress("UNCHECKED_CAST")
- val captor = ArgumentCaptor.forClass(PageResult::class.java)
- as ArgumentCaptor<PageResult<Int, Item>>
-
- TestSource().loadInitial(initialPosition, initialLoadSize, true, receiver)
-
- verify(receiver).onPageResult(captor.capture())
- verifyNoMoreInteractions(receiver)
- verifyRange(start, count, captor.value)
- }
-
- @Test
- fun initialLoad() {
- verifyInitialLoad(30, 40, 50, 40)
- verifyInitialLoad(0, 10, 5, 10)
- verifyInitialLoad(90, 10, 95, 10)
- }
-
private fun createCountedPagedList(
initialPosition: Int,
pageSize: Int = 20,
@@ -182,7 +159,6 @@
verifyNoMoreInteractions(callback)
}
-
@Test
fun prepend() {
val pagedList = createCountedPagedList(80)
@@ -311,6 +287,60 @@
}
@Test
+ fun initialLoadAsync() {
+ // Note: ignores Parameterized param
+ val asyncDataSource = AsyncListDataSource(ITEMS)
+ val dataSource = asyncDataSource.wrapAsContiguousWithoutPlaceholders()
+ val pagedList = ContiguousPagedList(
+ dataSource, mMainThread, mBackgroundThread, null,
+ PagedList.Config.Builder().setPageSize(10).build(), null)
+
+ assertTrue(pagedList.isEmpty())
+ drain()
+ assertTrue(pagedList.isEmpty())
+ asyncDataSource.flush()
+ assertTrue(pagedList.isEmpty())
+ mBackgroundThread.executeAll()
+ assertTrue(pagedList.isEmpty())
+
+ // Data source defers callbacks until flush, which posts result to main thread
+ mMainThread.executeAll()
+ assertFalse(pagedList.isEmpty())
+
+ }
+
+ @Test
+ fun addWeakCallbackEmpty() {
+ // Note: ignores Parameterized param
+ val asyncDataSource = AsyncListDataSource(ITEMS)
+ val dataSource = asyncDataSource.wrapAsContiguousWithoutPlaceholders()
+ val pagedList = ContiguousPagedList(
+ dataSource, mMainThread, mBackgroundThread, null,
+ PagedList.Config.Builder().setPageSize(10).build(), null)
+ val callback = mock(PagedList.Callback::class.java)
+
+ // capture empty snapshot
+ val emptySnapshot = pagedList.snapshot()
+ assertTrue(pagedList.isEmpty())
+ assertTrue(emptySnapshot.isEmpty())
+
+ // verify that adding callback notifies nothing going from empty -> empty
+ pagedList.addWeakCallback(emptySnapshot, callback)
+ verifyZeroInteractions(callback)
+ pagedList.removeWeakCallback(callback)
+
+ // data added in asynchronously
+ asyncDataSource.flush()
+ drain()
+ assertFalse(pagedList.isEmpty())
+
+ // verify that adding callback notifies insert going from empty -> content
+ pagedList.addWeakCallback(emptySnapshot, callback)
+ verify(callback).onInserted(0, pagedList.size)
+ verifyNoMoreInteractions(callback)
+ }
+
+ @Test
fun boundaryCallback_empty() {
@Suppress("UNCHECKED_CAST")
val boundaryCallback =
@@ -347,8 +377,7 @@
pagedList.loadAround(if (mCounted) 99 else 19)
drain()
verifyRange(80, 20, pagedList)
- verify(boundaryCallback).onItemAtEndLoaded(
- any(), eq(ITEMS.last()), eq(if (mCounted) 100 else 20))
+ verify(boundaryCallback).onItemAtEndLoaded(ITEMS.last())
verifyNoMoreInteractions(boundaryCallback)
@@ -371,7 +400,7 @@
// ... finally try prepend, see 0 items, which will dispatch front callback
pagedList.loadAround(0)
drain()
- verify(boundaryCallback).onItemAtFrontLoaded(any(), eq(ITEMS.first()), eq(100))
+ verify(boundaryCallback).onItemAtFrontLoaded(ITEMS.first())
verifyNoMoreInteractions(boundaryCallback)
}
diff --git a/paging/common/src/test/java/android/arch/paging/KeyedDataSourceTest.kt b/paging/common/src/test/java/android/arch/paging/KeyedDataSourceTest.kt
index 115fea2..e6c95e5 100644
--- a/paging/common/src/test/java/android/arch/paging/KeyedDataSourceTest.kt
+++ b/paging/common/src/test/java/android/arch/paging/KeyedDataSourceTest.kt
@@ -16,7 +16,6 @@
package android.arch.paging
-import org.junit.Assert.assertArrayEquals
import org.junit.Assert.assertEquals
import org.junit.Assert.assertNotNull
import org.junit.Assert.assertTrue
@@ -24,6 +23,7 @@
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.ArgumentCaptor
+import org.mockito.ArgumentMatchers.anyInt
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyNoMoreInteractions
@@ -33,31 +33,19 @@
// ----- STANDARD -----
- @Test
- fun loadInitial_validateTestDataSource() {
- val dataSource = ItemDataSource()
-
- // all
- assertEquals(ITEMS_BY_NAME_ID, dataSource.loadInitial(ITEMS_BY_NAME_ID.size))
-
- // 10
- assertEquals(ITEMS_BY_NAME_ID.subList(0, 10), dataSource.loadInitial(10))
-
- // too many
- assertEquals(ITEMS_BY_NAME_ID, dataSource.loadInitial(ITEMS_BY_NAME_ID.size + 10))
- }
-
private fun loadInitial(dataSource: ItemDataSource, key: Key?, initialLoadSize: Int,
- enablePlaceholders: Boolean): PageResult<Key, Item> {
+ enablePlaceholders: Boolean): PageResult<Item> {
@Suppress("UNCHECKED_CAST")
- val receiver = mock(PageResult.Receiver::class.java) as PageResult.Receiver<Key, Item>
+ val receiver = mock(PageResult.Receiver::class.java) as PageResult.Receiver<Item>
@Suppress("UNCHECKED_CAST")
val captor = ArgumentCaptor.forClass(PageResult::class.java)
- as ArgumentCaptor<PageResult<Key, Item>>
+ as ArgumentCaptor<PageResult<Item>>
- dataSource.loadInitial(key, initialLoadSize, enablePlaceholders, receiver)
+ val callback = DataSource.InitialLoadCallback(true, dataSource, receiver)
- verify(receiver).onPageResult(captor.capture())
+ dataSource.loadInitial(key, initialLoadSize, enablePlaceholders, callback)
+
+ verify(receiver).onPageResult(anyInt(), captor.capture())
verifyNoMoreInteractions(receiver)
assertNotNull(captor.value)
return captor.value
@@ -69,7 +57,7 @@
val result = loadInitial(dataSource, dataSource.getKey(ITEMS_BY_NAME_ID[49]), 10, true)
assertEquals(45, result.leadingNulls)
- assertEquals(ITEMS_BY_NAME_ID.subList(45, 55), result.page.items)
+ assertEquals(ITEMS_BY_NAME_ID.subList(45, 55), result.page)
assertEquals(45, result.trailingNulls)
}
@@ -81,7 +69,7 @@
val result = loadInitial(dataSource, dataSource.getKey(ITEMS_BY_NAME_ID[0]), 20, true)
assertEquals(0, result.leadingNulls)
- assertEquals(ITEMS_BY_NAME_ID.subList(0, 1), result.page.items)
+ assertEquals(ITEMS_BY_NAME_ID.subList(0, 1), result.page)
assertEquals(0, result.trailingNulls)
}
@@ -93,8 +81,8 @@
val key = dataSource.getKey(ITEMS_BY_NAME_ID.last())
val result = loadInitial(dataSource, key, 20, true)
- assertEquals(89, result.leadingNulls)
- assertEquals(ITEMS_BY_NAME_ID.subList(89, 100), result.page.items)
+ assertEquals(90, result.leadingNulls)
+ assertEquals(ITEMS_BY_NAME_ID.subList(90, 100), result.page)
assertEquals(0, result.trailingNulls)
}
@@ -106,7 +94,7 @@
val result = loadInitial(dataSource, null, 10, true)
assertEquals(0, result.leadingNulls)
- assertEquals(ITEMS_BY_NAME_ID.subList(0, 10), result.page.items)
+ assertEquals(ITEMS_BY_NAME_ID.subList(0, 10), result.page)
assertEquals(90, result.trailingNulls)
}
@@ -122,7 +110,7 @@
// do: load after was empty, so pass full size to load before, since this can incur larger
// loads than requested (see keyMatchesLastItem test)
assertEquals(95, result.leadingNulls)
- assertEquals(ITEMS_BY_NAME_ID.subList(95, 100), result.page.items)
+ assertEquals(ITEMS_BY_NAME_ID.subList(95, 100), result.page)
assertEquals(0, result.trailingNulls)
}
@@ -137,7 +125,7 @@
val result = loadInitial(dataSource, key, 10, false)
assertEquals(0, result.leadingNulls)
- assertEquals(ITEMS_BY_NAME_ID.subList(45, 55), result.page.items)
+ assertEquals(ITEMS_BY_NAME_ID.subList(45, 55), result.page)
assertEquals(0, result.trailingNulls)
}
@@ -150,7 +138,7 @@
val result = loadInitial(dataSource, key, 10, true)
assertEquals(0, result.leadingNulls)
- assertEquals(ITEMS_BY_NAME_ID.subList(45, 55), result.page.items)
+ assertEquals(ITEMS_BY_NAME_ID.subList(45, 55), result.page)
assertEquals(0, result.trailingNulls)
}
@@ -162,7 +150,7 @@
val result = loadInitial(dataSource, null, 10, true)
assertEquals(0, result.leadingNulls)
- assertEquals(ITEMS_BY_NAME_ID.subList(0, 10), result.page.items)
+ assertEquals(ITEMS_BY_NAME_ID.subList(0, 10), result.page)
assertEquals(0, result.trailingNulls)
}
@@ -177,7 +165,7 @@
val result = loadInitial(dataSource, key, 10, true)
assertEquals(0, result.leadingNulls)
- assertTrue(result.page.items.isEmpty())
+ assertTrue(result.page.isEmpty())
assertEquals(0, result.trailingNulls)
}
@@ -187,7 +175,7 @@
val result = loadInitial(dataSource, null, 10, true)
assertEquals(0, result.leadingNulls)
- assertTrue(result.page.items.isEmpty())
+ assertTrue(result.page.isEmpty())
assertEquals(0, result.trailingNulls)
}
@@ -197,21 +185,18 @@
fun loadBefore() {
val dataSource = ItemDataSource()
@Suppress("UNCHECKED_CAST")
- val receiver = mock(PageResult.Receiver::class.java)
- as PageResult.Receiver<Key, Item>
+ val callback = mock(DataSource.LoadCallback::class.java) as DataSource.LoadCallback<Item>
- dataSource.loadBefore(5, ITEMS_BY_NAME_ID[5], 5, receiver)
+ dataSource.loadBefore(5, ITEMS_BY_NAME_ID[5], 5, callback)
@Suppress("UNCHECKED_CAST")
- val argument = ArgumentCaptor.forClass(PageResult::class.java)
- as ArgumentCaptor<PageResult<Key, Item>>
- verify(receiver).postOnPageResult(argument.capture())
- verifyNoMoreInteractions(receiver)
+ val argument = ArgumentCaptor.forClass(List::class.java) as ArgumentCaptor<List<Item>>
+ verify(callback).onResult(argument.capture())
+ verifyNoMoreInteractions(callback)
val observed = argument.value
- assertEquals(PageResult.PREPEND, observed.type)
- assertEquals(ITEMS_BY_NAME_ID.subList(0, 5), observed.page.items)
+ assertEquals(ITEMS_BY_NAME_ID.subList(0, 5), observed)
}
internal data class Key(val name: String, val id: Int)
@@ -219,62 +204,53 @@
internal data class Item(
val name: String, val id: Int, val balance: Double, val address: String)
- internal class ItemDataSource(val counted: Boolean = true,
- val items: List<Item> = ITEMS_BY_NAME_ID)
+ internal class ItemDataSource(private val counted: Boolean = true,
+ private val items: List<Item> = ITEMS_BY_NAME_ID)
: KeyedDataSource<Key, Item>() {
+ override fun loadInitial(initialLoadKey: Key?, initialLoadSize: Int,
+ enablePlaceholders: Boolean, callback: InitialLoadCallback<Item>) {
+ val key = initialLoadKey ?: Key("", Integer.MAX_VALUE)
+ val start = Math.max(0, findFirstIndexAfter(key) - initialLoadSize / 2)
+ val endExclusive = Math.min(start + initialLoadSize, items.size)
+
+
+ if (enablePlaceholders && counted) {
+ callback.onResult(items.subList(start, endExclusive), start, items.size)
+ } else {
+ callback.onResult(items.subList(start, endExclusive))
+ }
+ }
+
+ override fun loadAfter(currentEndKey: Key, pageSize: Int, callback: LoadCallback<Item>) {
+ val start = findFirstIndexAfter(currentEndKey)
+ val endExclusive = Math.min(start + pageSize, items.size)
+
+ callback.onResult(items.subList(start, endExclusive))
+ }
+
+ override fun loadBefore(currentBeginKey: Key, pageSize: Int, callback: LoadCallback<Item>) {
+ val firstIndexBefore = findFirstIndexBefore(currentBeginKey)
+ val endExclusive = Math.max(0, firstIndexBefore + 1)
+ val start = Math.max(0, firstIndexBefore - pageSize + 1)
+
+ callback.onResult(items.subList(start, endExclusive))
+ }
override fun getKey(item: Item): Key {
return Key(item.name, item.id)
}
- override fun loadInitial(pageSize: Int): List<Item>? {
- // call loadAfter with a default key
- return loadAfter(Key("", Integer.MAX_VALUE), pageSize)
- }
-
- fun findFirstIndexAfter(key: Key): Int {
+ private fun findFirstIndexAfter(key: Key): Int {
return items.indices.firstOrNull {
KEY_COMPARATOR.compare(key, getKey(items[it])) < 0
} ?: items.size
}
- fun findFirstIndexBefore(key: Key): Int {
+ private fun findFirstIndexBefore(key: Key): Int {
return items.indices.reversed().firstOrNull {
KEY_COMPARATOR.compare(key, getKey(items[it])) > 0
} ?: -1
}
-
- override fun countItemsBefore(key: Key): Int {
- if (!counted) {
- return DataSource.COUNT_UNDEFINED
- }
-
- return findFirstIndexBefore(key) + 1
- }
-
- override fun countItemsAfter(key: Key): Int {
- if (!counted) {
- return DataSource.COUNT_UNDEFINED
- }
-
- return items.size - findFirstIndexAfter(key)
- }
-
- override fun loadAfter(key: Key, pageSize: Int): List<Item>? {
- val start = findFirstIndexAfter(key)
- val endExclusive = Math.min(start + pageSize, items.size)
-
- return items.subList(start, endExclusive)
- }
-
- override fun loadBefore(key: Key, pageSize: Int): List<Item>? {
- val firstIndexBefore = findFirstIndexBefore(key)
- val endExclusive = Math.max(0, firstIndexBefore + 1)
- val start = Math.max(0, firstIndexBefore - pageSize + 1)
-
- val list = items.subList(start, endExclusive)
- return list.reversed()
- }
}
companion object {
diff --git a/paging/common/src/test/java/android/arch/paging/PagedStorageTest.kt b/paging/common/src/test/java/android/arch/paging/PagedStorageTest.kt
index 92b6c87..8fb54e0 100644
--- a/paging/common/src/test/java/android/arch/paging/PagedStorageTest.kt
+++ b/paging/common/src/test/java/android/arch/paging/PagedStorageTest.kt
@@ -29,8 +29,8 @@
@RunWith(JUnit4::class)
class PagedStorageTest {
- private fun createPage(vararg strings: String): Page<Int, String> {
- return Page(strings.asList())
+ private fun createPage(vararg strings: String): List<String> {
+ return strings.asList()
}
@Test
@@ -216,7 +216,7 @@
@Test
fun insertOne() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(2, createPage("c", "d"), 3, 0, callback)
@@ -236,7 +236,7 @@
@Test
fun insertThree() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(2, createPage("c", "d"), 3, 0, callback)
@@ -273,7 +273,7 @@
@Test
fun insertLastFirst() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(6, createPage("g"), 0, 0, callback)
@@ -294,7 +294,7 @@
@Test(expected = IllegalArgumentException::class)
fun insertFailure_decreaseLast() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(2, createPage("c", "d"), 0, 0, callback)
@@ -305,7 +305,7 @@
@Test(expected = IllegalArgumentException::class)
fun insertFailure_increase() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(0, createPage("a", "b"), 3, 0, callback)
@@ -316,7 +316,7 @@
@Test
fun allocatePlaceholders_simple() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(2, createPage("c"), 2, 0, callback)
@@ -334,7 +334,7 @@
@Test
fun allocatePlaceholders_adoptPageSize() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(4, createPage("e"), 0, 0, callback)
@@ -352,7 +352,7 @@
@Test(expected = IllegalArgumentException::class)
fun allocatePlaceholders_cannotShrinkPageSize() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(4, createPage("e", "f"), 0, 0, callback)
@@ -365,7 +365,7 @@
@Test(expected = IllegalArgumentException::class)
fun allocatePlaceholders_cannotAdoptPageSize() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(2, createPage("c", "d"), 2, 0, callback)
@@ -377,7 +377,7 @@
@Test
fun get_placeholdersMulti() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(2, createPage("c", "d"), 3, 0, callback)
@@ -392,7 +392,7 @@
@Test
fun hasPage() {
val callback = mock(PagedStorage.Callback::class.java)
- val storage = PagedStorage<Int, String>()
+ val storage = PagedStorage<String>()
storage.init(4, createPage("e"), 0, 0, callback)
diff --git a/paging/common/src/test/java/android/arch/paging/PositionalDataSourceTest.kt b/paging/common/src/test/java/android/arch/paging/PositionalDataSourceTest.kt
new file mode 100644
index 0000000..34e0a57
--- /dev/null
+++ b/paging/common/src/test/java/android/arch/paging/PositionalDataSourceTest.kt
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package android.arch.paging
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.junit.runners.JUnit4
+
+@RunWith(JUnit4::class)
+class PositionalDataSourceTest {
+ @Test
+ fun computeFirstLoadPositionZero() {
+ assertEquals(0, PositionalDataSource.computeFirstLoadPosition(0, 30, 10, 100))
+ }
+
+ @Test
+ fun computeFirstLoadPositionRequestedPositionIncluded() {
+ assertEquals(10, PositionalDataSource.computeFirstLoadPosition(10, 10, 10, 100))
+ }
+
+ @Test
+ fun computeFirstLoadPositionRound() {
+ assertEquals(10, PositionalDataSource.computeFirstLoadPosition(13, 30, 10, 100))
+ }
+
+ @Test
+ fun computeFirstLoadPositionEndAdjusted() {
+ assertEquals(70, PositionalDataSource.computeFirstLoadPosition(99, 30, 10, 100))
+ }
+
+ @Test
+ fun computeFirstLoadPositionEndAdjustedAndAligned() {
+ assertEquals(70, PositionalDataSource.computeFirstLoadPosition(99, 35, 10, 100))
+ }
+}
diff --git a/paging/common/src/test/java/android/arch/paging/TiledDataSourceTest.kt b/paging/common/src/test/java/android/arch/paging/TiledDataSourceTest.kt
index 2b16fb2..b3ffdfb 100644
--- a/paging/common/src/test/java/android/arch/paging/TiledDataSourceTest.kt
+++ b/paging/common/src/test/java/android/arch/paging/TiledDataSourceTest.kt
@@ -1,45 +1,86 @@
+/*
+ * Copyright 2017 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
package android.arch.paging
-import org.junit.Assert.assertEquals
+import junit.framework.Assert.assertEquals
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import org.mockito.ArgumentCaptor
+import org.mockito.ArgumentMatchers.eq
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyNoMoreInteractions
import java.util.Collections
-
+@Suppress("DEPRECATION")
@RunWith(JUnit4::class)
class TiledDataSourceTest {
- @Test
- fun loadInitialEmpty() {
+
+ fun TiledDataSource<String>.loadInitial(startPosition: Int, count: Int, pageSize: Int)
+ : List<String> {
@Suppress("UNCHECKED_CAST")
- val receiver = mock(PageResult.Receiver::class.java) as PageResult.Receiver<Int, String>
- val dataSource = EmptyDataSource()
- dataSource.loadRangeInitial(0, 0, 1, 0, receiver)
+ val receiver = mock(PageResult.Receiver::class.java) as PageResult.Receiver<String>
+
+ val callback = DataSource.InitialLoadCallback(true, this, receiver)
+
+ this.loadInitial(startPosition, count, pageSize, callback)
@Suppress("UNCHECKED_CAST")
val argument = ArgumentCaptor.forClass(PageResult::class.java)
- as ArgumentCaptor<PageResult<Int, String>>
- verify(receiver).onPageResult(argument.capture())
+ as ArgumentCaptor<PageResult<String>>
+ verify(receiver).onPageResult(eq(PageResult.INIT), argument.capture())
verifyNoMoreInteractions(receiver)
val observed = argument.value
- assertEquals(PageResult.INIT, observed.type)
- assertEquals(Collections.EMPTY_LIST, observed.page.items)
+ return observed.page
}
- class EmptyDataSource : TiledDataSource<String>() {
- override fun countItems(): Int {
- return 0
+ @Test
+ fun loadInitialEmpty() {
+ class EmptyDataSource : TiledDataSource<String>() {
+ override fun countItems(): Int {
+ return 0
+ }
+
+ override fun loadRange(startPosition: Int, count: Int): List<String> {
+ return emptyList()
+ }
}
- override fun loadRange(startPosition: Int, count: Int): List<String> {
- @Suppress("UNCHECKED_CAST")
- return Collections.EMPTY_LIST as List<String>
- }
+ assertEquals(Collections.EMPTY_LIST, EmptyDataSource().loadInitial(0, 1, 5))
}
-}
\ No newline at end of file
+
+ @Test
+ fun loadInitialTooLong() {
+ val list = List(26) { "" + 'a' + it}
+ class AlphabetDataSource : TiledDataSource<String>() {
+ override fun countItems(): Int {
+ return list.size
+ }
+
+ override fun loadRange(startPosition: Int, count: Int): List<String> {
+ return list.subList(startPosition, startPosition + count)
+ }
+ }
+ // baseline behavior
+ assertEquals(list, AlphabetDataSource().loadInitial(0, 26, 10))
+ assertEquals(emptyList<String>(), AlphabetDataSource().loadInitial(0, 0, 10))
+ assertEquals(list, AlphabetDataSource().loadInitial(50, 26, 10))
+ }
+}
diff --git a/paging/common/src/test/java/android/arch/paging/TiledPagedListTest.kt b/paging/common/src/test/java/android/arch/paging/TiledPagedListTest.kt
index 6524008..10996a5 100644
--- a/paging/common/src/test/java/android/arch/paging/TiledPagedListTest.kt
+++ b/paging/common/src/test/java/android/arch/paging/TiledPagedListTest.kt
@@ -17,14 +17,13 @@
package android.arch.paging
import org.junit.Assert.assertEquals
+import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertSame
import org.junit.Assert.assertTrue
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
-import org.mockito.Mockito.any
-import org.mockito.Mockito.eq
import org.mockito.Mockito.mock
import org.mockito.Mockito.verify
import org.mockito.Mockito.verifyNoMoreInteractions
@@ -43,12 +42,12 @@
}
}
- private fun verifyLoadedPages(list: List<Item>, vararg loadedPages: Int, expected: List<Item> = ITEMS) {
+ private fun verifyLoadedPages(list: List<Item>, vararg loadedPages: Int) {
val loadedPageList = loadedPages.asList()
- assertEquals(expected.size, list.size)
+ assertEquals(ITEMS.size, list.size)
for (i in list.indices) {
if (loadedPageList.contains(i / PAGE_SIZE)) {
- assertSame("Index $i", expected[i], list[i])
+ assertSame("Index $i", ITEMS[i], list[i])
} else {
assertNull("Index $i", list[i])
}
@@ -70,21 +69,6 @@
}
@Test
- fun computeFirstLoadPosition_zero() {
- assertEquals(0, TiledPagedList.computeFirstLoadPosition(0, 30, 10, 100))
- }
-
- @Test
- fun computeFirstLoadPosition_requestedPositionIncluded() {
- assertEquals(0, TiledPagedList.computeFirstLoadPosition(10, 10, 10, 100))
- }
-
- @Test
- fun computeFirstLoadPosition_endAdjusted() {
- assertEquals(70, TiledPagedList.computeFirstLoadPosition(99, 30, 10, 100))
- }
-
- @Test
fun initialLoad_onePage() {
val pagedList = createTiledPagedList(loadPosition = 0, initPageCount = 1)
verifyLoadedPages(pagedList, 0, 1)
@@ -121,6 +105,56 @@
}
@Test
+ fun initialLoad_initializesLastKey() {
+ val pagedList = createTiledPagedList(loadPosition = 44, initPageCount = 2)
+ assertEquals(44, pagedList.lastKey)
+ }
+
+ @Test
+ fun initialLoadAsync() {
+ val dataSource = AsyncListDataSource(ITEMS)
+ val pagedList = TiledPagedList(
+ dataSource, mMainThread, mBackgroundThread, null,
+ PagedList.Config.Builder().setPageSize(10).build(), 0)
+
+ assertTrue(pagedList.isEmpty())
+ drain()
+ assertTrue(pagedList.isEmpty())
+ dataSource.flush()
+ assertTrue(pagedList.isEmpty())
+ mBackgroundThread.executeAll()
+ assertTrue(pagedList.isEmpty())
+
+ // Data source defers callbacks until flush, which posts result to main thread
+ mMainThread.executeAll()
+ assertFalse(pagedList.isEmpty())
+ }
+
+ @Test
+ fun addWeakCallbackEmpty() {
+ val dataSource = AsyncListDataSource(ITEMS)
+ val pagedList = TiledPagedList(
+ dataSource, mMainThread, mBackgroundThread, null,
+ PagedList.Config.Builder().setPageSize(10).build(), 0)
+
+ // capture empty snapshot
+ val emptySnapshot = pagedList.snapshot()
+ assertTrue(pagedList.isEmpty())
+ assertTrue(emptySnapshot.isEmpty())
+
+ // data added in asynchronously
+ dataSource.flush()
+ drain()
+ assertFalse(pagedList.isEmpty())
+
+ // verify that adding callback works with empty start point
+ val callback = mock(PagedList.Callback::class.java)
+ pagedList.addWeakCallback(emptySnapshot, callback)
+ verify(callback).onInserted(0, pagedList.size)
+ verifyNoMoreInteractions(callback)
+ }
+
+ @Test
fun append() {
val pagedList = createTiledPagedList(loadPosition = 0, initPageCount = 1)
val callback = mock(PagedList.Callback::class.java)
@@ -305,8 +339,8 @@
// callbacks posted, since creation often happens on BG thread
drain()
- verify(boundaryCallback).onItemAtFrontLoaded(any(), eq(ITEMS[0]), eq(2))
- verify(boundaryCallback).onItemAtEndLoaded(any(), eq(ITEMS[1]), eq(2))
+ verify(boundaryCallback).onItemAtFrontLoaded(ITEMS[0])
+ verify(boundaryCallback).onItemAtEndLoaded(ITEMS[1])
verifyNoMoreInteractions(boundaryCallback)
}
@@ -332,8 +366,8 @@
drain()
// first/last items loaded now, so callbacks dispatched
- verify(boundaryCallback).onItemAtFrontLoaded(any(), eq(ITEMS.first()), eq(45))
- verify(boundaryCallback).onItemAtEndLoaded(any(), eq(ITEMS.last()), eq(45))
+ verify(boundaryCallback).onItemAtFrontLoaded(ITEMS.first())
+ verify(boundaryCallback).onItemAtEndLoaded(ITEMS.last())
verifyNoMoreInteractions(boundaryCallback)
}
@@ -360,8 +394,8 @@
drain()
// items accessed, so now posted callbacks are run
- verify(boundaryCallback).onItemAtFrontLoaded(any(), eq(ITEMS.first()), eq(45))
- verify(boundaryCallback).onItemAtEndLoaded(any(), eq(ITEMS.last()), eq(45))
+ verify(boundaryCallback).onItemAtFrontLoaded(ITEMS.first())
+ verify(boundaryCallback).onItemAtEndLoaded(ITEMS.last())
verifyNoMoreInteractions(boundaryCallback)
}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemDataSource.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemDataSource.java
index 4690533..bbbfabb 100644
--- a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemDataSource.java
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/ItemDataSource.java
@@ -16,9 +16,10 @@
package android.arch.paging.integration.testapp;
-import android.arch.paging.BoundedDataSource;
+import android.arch.paging.PositionalDataSource;
import android.graphics.Color;
import android.support.annotation.ColorInt;
+import android.support.annotation.NonNull;
import java.util.ArrayList;
import java.util.List;
@@ -26,7 +27,7 @@
/**
* Sample data source with artificial data.
*/
-class ItemDataSource extends BoundedDataSource<Item> {
+class ItemDataSource extends PositionalDataSource<Item> {
private static final int COUNT = 500;
@ColorInt
@@ -39,18 +40,7 @@
private static int sGenerationId;
private final int mGenerationId = sGenerationId++;
- @Override
- public int countItems() {
- return COUNT;
- }
-
- @Override
- public List<Item> loadRange(int startPosition, int loadCount) {
- if (isInvalid()) {
- // abort!
- return null;
- }
-
+ private List<Item> loadRangeInternal(int startPosition, int loadCount) {
List<Item> items = new ArrayList<>();
int end = Math.min(COUNT, startPosition + loadCount);
int bgColor = COLORS[mGenerationId % COLORS.length];
@@ -63,11 +53,38 @@
for (int i = startPosition; i != end; i++) {
items.add(new Item(i, "item " + i, bgColor));
}
-
- if (isInvalid()) {
- // abort!
- return null;
- }
return items;
}
+
+ // TODO: open up this API in PositionalDataSource?
+ private static int computeFirstLoadPosition(int position, int firstLoadSize,
+ int pageSize, int size) {
+ int roundedPageStart = Math.round(position / pageSize) * pageSize;
+
+ // minimum start position is 0
+ roundedPageStart = Math.max(0, roundedPageStart);
+
+ // maximum start pos is that which will encompass end of list
+ int maximumLoadPage = ((size - firstLoadSize + pageSize - 1) / pageSize) * pageSize;
+ roundedPageStart = Math.min(maximumLoadPage, roundedPageStart);
+
+ return roundedPageStart;
+ }
+
+ @Override
+ public void loadInitial(int requestedStartPosition, int requestedLoadSize,
+ int pageSize, @NonNull InitialLoadCallback<Item> callback) {
+ requestedStartPosition = computeFirstLoadPosition(
+ requestedStartPosition, requestedLoadSize, pageSize, COUNT);
+
+ requestedLoadSize = Math.min(COUNT - requestedStartPosition, requestedLoadSize);
+ List<Item> data = loadRangeInternal(requestedStartPosition, requestedLoadSize);
+ callback.onResult(data, requestedStartPosition, COUNT);
+ }
+
+ @Override
+ public void loadRange(int startPosition, int count, @NonNull LoadCallback<Item> callback) {
+ List<Item> data = loadRangeInternal(startPosition, count);
+ callback.onResult(data);
+ }
}
diff --git a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/PagedListItemViewModel.java b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/PagedListItemViewModel.java
index 974eab9..be14bc1 100644
--- a/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/PagedListItemViewModel.java
+++ b/paging/integration-tests/testapp/src/main/java/android/arch/paging/integration/testapp/PagedListItemViewModel.java
@@ -27,10 +27,24 @@
*/
@SuppressWarnings("WeakerAccess")
public class PagedListItemViewModel extends ViewModel {
- private LiveData<PagedList<Item>> mLivePagedList;
private ItemDataSource mDataSource;
private final Object mDataSourceLock = new Object();
+ private final DataSource.Factory<Integer, Item> mFactory =
+ new DataSource.Factory<Integer, Item>() {
+ @Override
+ public DataSource<Integer, Item> create() {
+ ItemDataSource newDataSource = new ItemDataSource();
+ synchronized (mDataSourceLock) {
+ mDataSource = newDataSource;
+ return mDataSource;
+ }
+ }
+ };
+
+ private LiveData<PagedList<Item>> mLivePagedList =
+ new LivePagedListBuilder<>(mFactory, 20).build();
+
void invalidateList() {
synchronized (mDataSourceLock) {
if (mDataSource != null) {
@@ -40,22 +54,6 @@
}
LiveData<PagedList<Item>> getLivePagedList() {
- if (mLivePagedList == null) {
- mLivePagedList = new LivePagedListBuilder<Integer, Item>()
- .setPagingConfig(20)
- .setDataSourceFactory(new DataSource.Factory<Integer, Item>() {
- @Override
- public DataSource<Integer, Item> create() {
- ItemDataSource newDataSource = new ItemDataSource();
- synchronized (mDataSourceLock) {
- mDataSource = newDataSource;
- return mDataSource;
- }
- }
- })
- .build();
- }
-
return mLivePagedList;
}
}
diff --git a/paging/runtime/src/androidTest/java/android/arch/paging/PagedStorageDiffHelperTest.kt b/paging/runtime/src/androidTest/java/android/arch/paging/PagedStorageDiffHelperTest.kt
index 64501f7..b64b27b 100644
--- a/paging/runtime/src/androidTest/java/android/arch/paging/PagedStorageDiffHelperTest.kt
+++ b/paging/runtime/src/androidTest/java/android/arch/paging/PagedStorageDiffHelperTest.kt
@@ -35,17 +35,17 @@
@Test
fun sameListNoUpdates() {
validateTwoListDiff(
- PagedStorage(5, createPage("a", "b", "c"), 5),
- PagedStorage(5, createPage("a", "b", "c"), 5)) {
+ PagedStorage(5, listOf("a", "b", "c"), 5),
+ PagedStorage(5, listOf("a", "b", "c"), 5)) {
verifyZeroInteractions(it)
}
}
@Test
fun sameListNoUpdatesPlaceholder() {
- val storageNoPlaceholder = PagedStorage(0, createPage("a", "b", "c"), 10)
+ val storageNoPlaceholder = PagedStorage(0, listOf("a", "b", "c"), 10)
- val storageWithPlaceholder = PagedStorage(0, createPage("a", "b", "c"), 10)
+ val storageWithPlaceholder = PagedStorage(0, listOf("a", "b", "c"), 10)
storageWithPlaceholder.allocatePlaceholders(3, 0, 3,
/* ignored */ mock(PagedStorage.Callback::class.java))
@@ -64,8 +64,8 @@
@Test
fun appendFill() {
validateTwoListDiff(
- PagedStorage(5, createPage("a", "b"), 5),
- PagedStorage(5, createPage("a", "b", "c"), 4)) {
+ PagedStorage(5, listOf("a", "b"), 5),
+ PagedStorage(5, listOf("a", "b", "c"), 4)) {
verify(it).onRemoved(11, 1)
verify(it).onInserted(7, 1)
// NOTE: ideally would be onChanged(7, 1, null)
@@ -76,8 +76,8 @@
@Test
fun prependFill() {
validateTwoListDiff(
- PagedStorage(5, createPage("b", "c"), 5),
- PagedStorage(4, createPage("a", "b", "c"), 5)) {
+ PagedStorage(5, listOf("b", "c"), 5),
+ PagedStorage(4, listOf("a", "b", "c"), 5)) {
verify(it).onRemoved(0, 1)
verify(it).onInserted(4, 1)
//NOTE: ideally would be onChanged(4, 1, null);
@@ -88,8 +88,8 @@
@Test
fun change() {
validateTwoListDiff(
- PagedStorage(5, createPage("a1", "b1", "c1"), 5),
- PagedStorage(5, createPage("a2", "b1", "c2"), 5)) {
+ PagedStorage(5, listOf("a1", "b1", "c1"), 5),
+ PagedStorage(5, listOf("a2", "b1", "c2"), 5)) {
verify(it).onChanged(5, 1, null)
verify(it).onChanged(7, 1, null)
verifyNoMoreInteractions(it)
@@ -108,12 +108,8 @@
}
}
- private fun createPage(vararg items: String): Page<Int, String> {
- return Page(items.toList())
- }
-
- private fun validateTwoListDiff(oldList: PagedStorage<*, String>,
- newList: PagedStorage<*, String>,
+ private fun validateTwoListDiff(oldList: PagedStorage<String>,
+ newList: PagedStorage<String>,
validator: (callback: ListUpdateCallback) -> Unit) {
val diffResult = PagedStorageDiffHelper.computeDiff(
oldList, newList, DIFF_CALLBACK)
diff --git a/paging/runtime/src/androidTest/java/android/arch/paging/StringPagedList.kt b/paging/runtime/src/androidTest/java/android/arch/paging/StringPagedList.kt
index c2e5ec7..48d51bc 100644
--- a/paging/runtime/src/androidTest/java/android/arch/paging/StringPagedList.kt
+++ b/paging/runtime/src/androidTest/java/android/arch/paging/StringPagedList.kt
@@ -17,13 +17,13 @@
package android.arch.paging
class StringPagedList constructor(leadingNulls: Int, trailingNulls: Int, vararg items: String)
- : PagedList<String>(PagedStorage<Int, String>(), TestExecutor(), TestExecutor(), null,
+ : PagedList<String>(PagedStorage<String>(), TestExecutor(), TestExecutor(), null,
PagedList.Config.Builder().setPageSize(1).build()), PagedStorage.Callback {
init {
@Suppress("UNCHECKED_CAST")
- val keyedStorage = mStorage as PagedStorage<Int, String>
+ val keyedStorage = mStorage as PagedStorage<String>
keyedStorage.init(leadingNulls,
- Page<Int, String>(null, items.toList(), null),
+ items.toList(),
trailingNulls,
0,
this)
diff --git a/paging/runtime/src/main/java/android/arch/paging/LivePagedListBuilder.java b/paging/runtime/src/main/java/android/arch/paging/LivePagedListBuilder.java
index ee1810b..2edbcdf 100644
--- a/paging/runtime/src/main/java/android/arch/paging/LivePagedListBuilder.java
+++ b/paging/runtime/src/main/java/android/arch/paging/LivePagedListBuilder.java
@@ -25,42 +25,76 @@
import java.util.concurrent.Executor;
+/**
+ * Builder for {@code LiveData<PagedList>}, given a {@link DataSource.Factory} and a
+ * {@link PagedList.Config}.
+ * <p>
+ * The required parameters are in the constructor, so you can simply construct and build, or
+ * optionally enable extra features (such as initial load key, or BoundaryCallback.
+ *
+ * @param <Key> Type of input valued used to load data from the DataSource. Must be integer if
+ * you're using PositionalDataSource.
+ * @param <Value> Item type being presented.
+ */
public class LivePagedListBuilder<Key, Value> {
private Key mInitialLoadKey;
private PagedList.Config mConfig;
private DataSource.Factory<Key, Value> mDataSourceFactory;
private PagedList.BoundaryCallback mBoundaryCallback;
- private Executor mMainThreadExecutor;
private Executor mBackgroundThreadExecutor;
- @SuppressWarnings("WeakerAccess")
+ /**
+ * Creates a LivePagedListBuilder with required parameters.
+ *
+ * @param dataSourceFactory DataSource factory providing DataSource generations.
+ * @param config Paging configuration.
+ */
+ public LivePagedListBuilder(@NonNull DataSource.Factory<Key, Value> dataSourceFactory,
+ @NonNull PagedList.Config config) {
+ mDataSourceFactory = dataSourceFactory;
+ mConfig = config;
+ }
+
+ /**
+ * Creates a LivePagedListBuilder with required parameters.
+ * <p>
+ * This method is a convenience for
+ * <pre>
+ * LivePagedListBuilder(dataSourceFactory,
+ * PagedList.Config.Builder().setPageSize(pageSize)).build()}
+ * </pre>
+ *
+ * @param dataSourceFactory
+ * @param pageSize
+ */
+ public LivePagedListBuilder(@NonNull DataSource.Factory<Key, Value> dataSourceFactory,
+ int pageSize) {
+ this(dataSourceFactory, new PagedList.Config.Builder().setPageSize(pageSize).build());
+ }
+
+ /**
+ * First loading key passed to the first PagedList/DataSource.
+ * <p>
+ * When a new PagedList/DataSource pair is created after the first, it acquires a load key from
+ * the previous generation so that data is loaded around the position already being observed.
+ *
+ * @param key Initial load key passed to the first PagedList/DataSource.
+ * @return this
+ */
@NonNull
public LivePagedListBuilder<Key, Value> setInitialLoadKey(@Nullable Key key) {
mInitialLoadKey = key;
return this;
}
- @SuppressWarnings("WeakerAccess")
- @NonNull
- public LivePagedListBuilder<Key, Value> setPagingConfig(@NonNull PagedList.Config config) {
- mConfig = config;
- return this;
- }
-
- @SuppressWarnings("WeakerAccess")
- @NonNull
- public LivePagedListBuilder<Key, Value> setPagingConfig(int pageSize) {
- mConfig = new PagedList.Config.Builder().setPageSize(pageSize).build();
- return this;
- }
-
- @NonNull
- public LivePagedListBuilder<Key, Value> setDataSourceFactory(
- @NonNull DataSource.Factory<Key, Value> dataSourceFactory) {
- mDataSourceFactory = dataSourceFactory;
- return this;
- }
-
+ /**
+ * Sets a {@link PagedList.BoundaryCallback} on each PagedList created.
+ * <p>
+ * This can be used to
+ *
+ * @param boundaryCallback The boundary callback for listening to PagedList load state.
+ * @return this
+ */
@SuppressWarnings("unused")
@NonNull
public LivePagedListBuilder<Key, Value> setBoundaryCallback(
@@ -69,14 +103,15 @@
return this;
}
- @SuppressWarnings("unused")
- @NonNull
- public LivePagedListBuilder<Key, Value> setMainThreadExecutor(
- @NonNull Executor mainThreadExecutor) {
- mMainThreadExecutor = mainThreadExecutor;
- return this;
- }
-
+ /**
+ * Sets executor which will be used for background loading of pages.
+ * <p>
+ * Does not affect initial load, which will be always be done on done on the Arch components
+ * I/O thread.
+ *
+ * @param backgroundThreadExecutor Executor for background DataSource loading.
+ * @return this
+ */
@SuppressWarnings("unused")
@NonNull
public LivePagedListBuilder<Key, Value> setBackgroundThreadExecutor(
@@ -85,6 +120,14 @@
return this;
}
+ /**
+ * Constructs the {@code LiveData<PagedList>}.
+ * <p>
+ * No work (such as loading) is done immediately, the creation of the first PagedList is is
+ * deferred until the LiveData is observed.
+ *
+ * @return The LiveData of PagedLists
+ */
@NonNull
public LiveData<PagedList<Value>> build() {
if (mConfig == null) {
@@ -93,20 +136,17 @@
if (mDataSourceFactory == null) {
throw new IllegalArgumentException("DataSource.Factory must be provided");
}
- if (mMainThreadExecutor == null) {
- mMainThreadExecutor = ArchTaskExecutor.getMainThreadExecutor();
- }
if (mBackgroundThreadExecutor == null) {
mBackgroundThreadExecutor = ArchTaskExecutor.getIOThreadExecutor();
}
return create(mInitialLoadKey, mConfig, mBoundaryCallback, mDataSourceFactory,
- mMainThreadExecutor, mBackgroundThreadExecutor);
+ ArchTaskExecutor.getMainThreadExecutor(), mBackgroundThreadExecutor);
}
@AnyThread
@NonNull
- public static <Key, Value> LiveData<PagedList<Value>> create(
+ private static <Key, Value> LiveData<PagedList<Value>> create(
@Nullable final Key initialLoadKey,
@NonNull final PagedList.Config config,
@Nullable final PagedList.BoundaryCallback boundaryCallback,
diff --git a/paging/runtime/src/main/java/android/arch/paging/LivePagedListProvider.java b/paging/runtime/src/main/java/android/arch/paging/LivePagedListProvider.java
index e0a03cb..44b71a8 100644
--- a/paging/runtime/src/main/java/android/arch/paging/LivePagedListProvider.java
+++ b/paging/runtime/src/main/java/android/arch/paging/LivePagedListProvider.java
@@ -22,45 +22,30 @@
import android.support.annotation.Nullable;
import android.support.annotation.WorkerThread;
+// NOTE: Room 1.0 depends on this class, so it should not be removed
+// until Room switches to using DataSource.Factory directly
/**
* Provides a {@code LiveData<PagedList>}, given a means to construct a DataSource.
* <p>
* Return type for data-loading system of an application or library to produce a
* {@code LiveData<PagedList>}, while leaving the details of the paging mechanism up to the
* consumer.
- * <p>
- * If you're using Room, it can generate a LivePagedListProvider from a query:
- * <pre>
- * {@literal @}Dao
- * interface UserDao {
- * {@literal @}Query("SELECT * FROM user ORDER BY lastName ASC")
- * public abstract LivePagedListProvider<Integer, User> usersByLastName();
- * }</pre>
- * In the above sample, {@code Integer} is used because it is the {@code Key} type of
- * {@link TiledDataSource}. Currently, Room can only generate a {@code LIMIT}/{@code OFFSET},
- * position based loader that uses TiledDataSource under the hood, and specifying {@code Integer}
- * here lets you pass an initial loading position as an integer.
- * <p>
- * In the future, Room plans to offer other key types to support paging content with a
- * {@link KeyedDataSource}.
*
* @param <Key> Type of input valued used to load data from the DataSource. Must be integer if
- * you're using TiledDataSource.
+ * you're using PositionalDataSource.
* @param <Value> Data type produced by the DataSource, and held by the PagedLists.
*
* @see PagedListAdapter
* @see DataSource
* @see PagedList
*
- * @deprecated To construct a {@code LiveData<PagedList>}, use {@link LivePagedListBuilder}, which
- * provides the same construction capability with more customization, and better defaults. The role
+ * @deprecated use {@link LivePagedListBuilder} to construct a {@code LiveData<PagedList>}. It
+ * provides the same construction capability with more customization, and simpler defaults. The role
* of DataSource construction has been separated out to {@link DataSource.Factory} to access or
* provide a self-invalidating sequence of DataSources. If you were acquiring this from Room, you
- * can switch to having your Dao return a {@link DataSource.Factory} instead, and create a LiveData
- * of PagedList with a {@link LivePagedListBuilder}.
+ * can switch to having your Dao return a {@link DataSource.Factory} instead, and create a
+ * {@code LiveData<PagedList>} with a {@link LivePagedListBuilder}.
*/
-// NOTE: Room 1.0 depends on this class, so it should not be removed
-// until Room switches to using DataSource.Factory directly
@Deprecated
public abstract class LivePagedListProvider<Key, Value> implements DataSource.Factory<Key, Value> {
@@ -93,10 +78,8 @@
@AnyThread
@NonNull
public LiveData<PagedList<Value>> create(@Nullable Key initialLoadKey, int pageSize) {
- return new LivePagedListBuilder<Key, Value>()
+ return new LivePagedListBuilder<>(this, pageSize)
.setInitialLoadKey(initialLoadKey)
- .setPagingConfig(pageSize)
- .setDataSourceFactory(this)
.build();
}
@@ -116,10 +99,8 @@
@NonNull
public LiveData<PagedList<Value>> create(@Nullable Key initialLoadKey,
@NonNull PagedList.Config config) {
- return new LivePagedListBuilder<Key, Value>()
+ return new LivePagedListBuilder<>(this, config)
.setInitialLoadKey(initialLoadKey)
- .setPagingConfig(config)
- .setDataSourceFactory(this)
.build();
}
}
diff --git a/paging/runtime/src/main/java/android/arch/paging/PagedListAdapter.java b/paging/runtime/src/main/java/android/arch/paging/PagedListAdapter.java
index 89b9c2e..a8158c2 100644
--- a/paging/runtime/src/main/java/android/arch/paging/PagedListAdapter.java
+++ b/paging/runtime/src/main/java/android/arch/paging/PagedListAdapter.java
@@ -44,18 +44,14 @@
* {@literal @}Dao
* interface UserDao {
* {@literal @}Query("SELECT * FROM user ORDER BY lastName ASC")
- * public abstract LivePagedListProvider<Integer, User> usersByLastName();
+ * public abstract DataSource.Factory<Integer, User> usersByLastName();
* }
*
* class MyViewModel extends ViewModel {
* public final LiveData<PagedList<User>> usersList;
* public MyViewModel(UserDao userDao) {
- * usersList = userDao.usersByLastName().create(
- * /* initial load position {@literal *}/ 0,
- * new PagedList.Config.Builder()
- * .setPageSize(50)
- * .setPrefetchDistance(50)
- * .build());
+ * usersList = LivePagedListBuilder<>(
+ * userDao.usersByLastName(), /* page size {@literal *}/ 20).build();
* }
* }
*
diff --git a/paging/runtime/src/main/java/android/arch/paging/PagedListAdapterHelper.java b/paging/runtime/src/main/java/android/arch/paging/PagedListAdapterHelper.java
index 51a6e37..7a0b81a 100644
--- a/paging/runtime/src/main/java/android/arch/paging/PagedListAdapterHelper.java
+++ b/paging/runtime/src/main/java/android/arch/paging/PagedListAdapterHelper.java
@@ -48,18 +48,14 @@
* {@literal @}Dao
* interface UserDao {
* {@literal @}Query("SELECT * FROM user ORDER BY lastName ASC")
- * public abstract LivePagedListProvider<Integer, User> usersByLastName();
+ * public abstract DataSource.Factory<Integer, User> usersByLastName();
* }
*
* class MyViewModel extends ViewModel {
* public final LiveData<PagedList<User>> usersList;
* public MyViewModel(UserDao userDao) {
- * usersList = userDao.usersByLastName().create(
- * /* initial load position {@literal *}/ 0,
- * new PagedList.Config.Builder()
- * .setPageSize(50)
- * .setPrefetchDistance(50)
- * .build());
+ * usersList = LivePagedListBuilder<>(
+ * userDao.usersByLastName(), /* page size {@literal *}/ 20).build();
* }
* }
*
diff --git a/paging/runtime/src/main/java/android/arch/paging/PagedStorageDiffHelper.java b/paging/runtime/src/main/java/android/arch/paging/PagedStorageDiffHelper.java
index 6fc7039..d991b72 100644
--- a/paging/runtime/src/main/java/android/arch/paging/PagedStorageDiffHelper.java
+++ b/paging/runtime/src/main/java/android/arch/paging/PagedStorageDiffHelper.java
@@ -26,8 +26,8 @@
}
static <T> DiffUtil.DiffResult computeDiff(
- final PagedStorage<?, T> oldList,
- final PagedStorage<?, T> newList,
+ final PagedStorage<T> oldList,
+ final PagedStorage<T> newList,
final DiffCallback<T> diffCallback) {
final int oldOffset = oldList.computeLeadingNulls();
final int newOffset = newList.computeLeadingNulls();
@@ -131,8 +131,8 @@
* immediately after dispatching this diff.
*/
static <T> void dispatchDiff(ListUpdateCallback callback,
- final PagedStorage<?, T> oldList,
- final PagedStorage<?, T> newList,
+ final PagedStorage<T> oldList,
+ final PagedStorage<T> newList,
final DiffUtil.DiffResult diffResult) {
final int trailingOld = oldList.computeTrailingNulls();
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserDao.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserDao.java
index cb2bb03..0b184a9 100644
--- a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserDao.java
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/dao/UserDao.java
@@ -190,8 +190,12 @@
@Query("SELECT * FROM user where mAge > :age")
public abstract LivePagedListProvider<Integer, User> loadPagedByAge_legacy(int age);
+ // TODO: switch to PositionalDataSource once Room supports it
@Query("SELECT * FROM user ORDER BY mAge DESC")
- public abstract TiledDataSource<User> loadUsersByAgeDesc();
+ public abstract DataSource.Factory<Integer, User> loadUsersByAgeDesc();
+
+ @Query("SELECT * FROM user ORDER BY mAge DESC")
+ public abstract TiledDataSource<User> loadUsersByAgeDesc_legacy();
@Query("DELETE FROM User WHERE mId IN (:ids) AND mAge == :age")
public abstract int deleteByAgeAndIds(int age, List<Integer> ids);
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/DataSourceFactoryTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/DataSourceFactoryTest.java
index c546531..b54abe8 100644
--- a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/DataSourceFactoryTest.java
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/DataSourceFactoryTest.java
@@ -63,12 +63,12 @@
validateUsersAsPagedList(new LivePagedListFactory() {
@Override
public LiveData<PagedList<User>> create() {
- return new LivePagedListBuilder<Integer, User>()
- .setPagingConfig(new PagedList.Config.Builder()
+ return new LivePagedListBuilder<>(
+ mUserDao.loadPagedByAge(3),
+ new PagedList.Config.Builder()
.setPageSize(10)
.setPrefetchDistance(1)
.setInitialLoadSizeHint(10).build())
- .setDataSourceFactory(mUserDao.loadPagedByAge(3))
.build();
}
});
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LimitOffsetDataSourceTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LimitOffsetDataSourceTest.java
index 8226759..f0285a0 100644
--- a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LimitOffsetDataSourceTest.java
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/paging/LimitOffsetDataSourceTest.java
@@ -45,8 +45,17 @@
mUserDao.deleteEverything();
}
+ // TODO: delete this and factory abstraction when LivePagedListProvider is removed
+ @Test
+ public void limitOffsetDataSource_legacyTiledDataSource() {
+ // Simple verification that loading a TiledDataSource still works.
+ LimitOffsetDataSource<User> dataSource =
+ (LimitOffsetDataSource<User>) mUserDao.loadUsersByAgeDesc_legacy();
+ assertThat(dataSource.countItems(), is(0));
+ }
+
private LimitOffsetDataSource<User> loadUsersByAgeDesc() {
- return (LimitOffsetDataSource<User>) mUserDao.loadUsersByAgeDesc();
+ return (LimitOffsetDataSource<User>) mUserDao.loadUsersByAgeDesc().create();
}
@Test
diff --git a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/QueryTransactionTest.java b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/QueryTransactionTest.java
index 291cfd6..f076cf1 100644
--- a/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/QueryTransactionTest.java
+++ b/room/integration-tests/testapp/src/androidTest/java/android/arch/persistence/room/integration/testapp/test/QueryTransactionTest.java
@@ -203,10 +203,8 @@
@Test
public void pagedList() {
- LiveData<PagedList<Entity1>> pagedList = new LivePagedListBuilder<Integer, Entity1>()
- .setDataSourceFactory(mDao.pagedList())
- .setPagingConfig(10)
- .build();
+ LiveData<PagedList<Entity1>> pagedList =
+ new LivePagedListBuilder<>(mDao.pagedList(), 10).build();
observeForever(pagedList);
drain();
assertThat(sStartedTransactionCount.get(), is(mUseTransactionDao ? 0 : 0));
@@ -228,6 +226,7 @@
mDao.insert(new Entity1(2, "bar"));
drain();
resetTransactionCount();
+ @SuppressWarnings("deprecation")
TiledDataSource<Entity1> dataSource = mDao.dataSource();
dataSource.loadRange(0, 10);
assertThat(sStartedTransactionCount.get(), is(mUseTransactionDao ? 1 : 0));
diff --git a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/CustomerViewModel.java b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/CustomerViewModel.java
index 89d16b7..d8cd8d4 100644
--- a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/CustomerViewModel.java
+++ b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/CustomerViewModel.java
@@ -83,13 +83,12 @@
private static <K> LiveData<PagedList<Customer>> getLivePagedList(
K initialLoadKey, DataSource.Factory<K, Customer> dataSourceFactory) {
- return new LivePagedListBuilder<K, Customer>()
+ PagedList.Config config = new PagedList.Config.Builder()
+ .setPageSize(10)
+ .setEnablePlaceholders(false)
+ .build();
+ return new LivePagedListBuilder<>(dataSourceFactory, config)
.setInitialLoadKey(initialLoadKey)
- .setPagingConfig(new PagedList.Config.Builder()
- .setPageSize(10)
- .setEnablePlaceholders(false)
- .build())
- .setDataSourceFactory(dataSourceFactory)
.build();
}
diff --git a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/RoomPagedListActivity.java b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/RoomPagedListActivity.java
index cdd464e..0c79aee 100644
--- a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/RoomPagedListActivity.java
+++ b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/RoomPagedListActivity.java
@@ -16,7 +16,6 @@
package android.arch.persistence.room.integration.testapp;
-import android.arch.lifecycle.LifecycleRegistry;
import android.arch.lifecycle.LiveData;
import android.arch.lifecycle.Observer;
import android.arch.lifecycle.ViewModelProviders;
@@ -75,7 +74,7 @@
mAdapter.setList(items);
}
});
- final Button button = findViewById(R.id.button);
+ final Button button = findViewById(R.id.addButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
@@ -114,11 +113,4 @@
protected boolean useKeyedQuery() {
return false;
}
-
- private LifecycleRegistry mLifecycleRegistry = new LifecycleRegistry(this);
-
- @Override
- public LifecycleRegistry getLifecycle() {
- return mLifecycleRegistry;
- }
}
diff --git a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/LastNameAscCustomerDataSource.java b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/LastNameAscCustomerDataSource.java
index a38d6ae..2db543b 100644
--- a/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/LastNameAscCustomerDataSource.java
+++ b/room/integration-tests/testapp/src/main/java/android/arch/persistence/room/integration/testapp/database/LastNameAscCustomerDataSource.java
@@ -21,6 +21,7 @@
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
+import java.util.Collections;
import java.util.List;
import java.util.Set;
@@ -60,7 +61,6 @@
@Override
public boolean isInvalid() {
mDb.getInvalidationTracker().refreshVersionsSync();
-
return super.isInvalid();
}
@@ -76,30 +76,48 @@
}
@Override
- public int countItemsBefore(@NonNull String customerName) {
- return mCustomerDao.customerNameCountBefore(customerName);
+ public void loadInitial(@Nullable String customerName, int initialLoadSize,
+ boolean enablePlaceholders, @NonNull InitialLoadCallback<Customer> callback) {
+ List<Customer> list;
+ if (customerName != null) {
+ // initial keyed load - load before 'customerName',
+ // and load after last item in before list
+ int pageSize = initialLoadSize / 2;
+ String key = customerName;
+ list = mCustomerDao.customerNameLoadBefore(key, pageSize);
+ Collections.reverse(list);
+ if (!list.isEmpty()) {
+ key = getKey(list.get(list.size() - 1));
+ }
+ list.addAll(mCustomerDao.customerNameLoadAfter(key, pageSize));
+ } else {
+ list = mCustomerDao.customerNameInitial(initialLoadSize);
+ }
+
+ if (enablePlaceholders && !list.isEmpty()) {
+ String firstKey = getKey(list.get(0));
+ String lastKey = getKey(list.get(list.size() - 1));
+
+ // only bother counting if placeholders are desired
+ final int position = mCustomerDao.customerNameCountBefore(firstKey);
+ final int count = position + list.size() + mCustomerDao.customerNameCountAfter(lastKey);
+ callback.onResult(list, position, count);
+ } else {
+ callback.onResult(list);
+ }
}
@Override
- public int countItemsAfter(@NonNull String customerName) {
- return mCustomerDao.customerNameCountAfter(customerName);
+ public void loadAfter(@NonNull String currentEndKey, int pageSize,
+ @NonNull LoadCallback<Customer> callback) {
+ callback.onResult(mCustomerDao.customerNameLoadAfter(currentEndKey, pageSize));
}
- @Nullable
@Override
- public List<Customer> loadInitial(int pageSize) {
- return mCustomerDao.customerNameInitial(pageSize);
- }
-
- @Nullable
- @Override
- public List<Customer> loadBefore(@NonNull String customerName, int pageSize) {
- return mCustomerDao.customerNameLoadBefore(customerName, pageSize);
- }
-
- @Nullable
- @Override
- public List<Customer> loadAfter(@Nullable String customerName, int pageSize) {
- return mCustomerDao.customerNameLoadAfter(customerName, pageSize);
+ public void loadBefore(@NonNull String currentBeginKey, int pageSize,
+ @NonNull LoadCallback<Customer> callback) {
+ List<Customer> list = mCustomerDao.customerNameLoadBefore(currentBeginKey, pageSize);
+ Collections.reverse(list);
+ callback.onResult(list);
}
}
diff --git a/room/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml b/room/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml
index 71dae1b..34e4491 100644
--- a/room/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml
+++ b/room/integration-tests/testapp/src/main/res/layout/activity_recycler_view.xml
@@ -35,7 +35,7 @@
android:paddingTop="@dimen/activity_vertical_margin"
/>
<Button
- android:id="@+id/button"
+ android:id="@+id/addButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"