summaryrefslogtreecommitdiff
path: root/android/arch/paging/TiledDataSource.java
blob: 36be423dd2e74942a1cc11708572bb66aa64d944 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
/*
 * 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.WorkerThread;

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&lt;User> loadUsersByAgeDesc();
 * }</pre>
 *
 * 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&lt;User> userNameLimitOffset(int limit, int offset);
 * }
 *
 * public class OffsetUserQueryDataSource extends TiledDataSource&lt;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&lt;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&lt;User> loadRange(int startPosition, int loadCount) {
 *         return mUserDao.userNameLimitOffset(loadCount, startPosition);
 *     }
 * }</pre>
 *
 * @param <Type> Type of items being loaded by the TiledDataSource.
 */
public abstract class TiledDataSource<Type> extends DataSource<Integer, Type> {

    /**
     * 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
    @Override
    public abstract int countItems();

    @Override
    boolean isContiguous() {
        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);

    final 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);
        }
    }
}