1/* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package androidx.paging.integration.testapp; 18 19import android.graphics.Color; 20 21import androidx.annotation.ColorInt; 22import androidx.annotation.NonNull; 23import androidx.paging.PositionalDataSource; 24 25import java.util.ArrayList; 26import java.util.List; 27 28/** 29 * Sample data source with artificial data. 30 */ 31class ItemDataSource extends PositionalDataSource<Item> { 32 private static final int COUNT = 500; 33 34 @ColorInt 35 private static final int[] COLORS = new int[] { 36 Color.RED, 37 Color.BLUE, 38 Color.BLACK, 39 }; 40 41 private static int sGenerationId; 42 private final int mGenerationId = sGenerationId++; 43 44 private List<Item> loadRangeInternal(int startPosition, int loadCount) { 45 List<Item> items = new ArrayList<>(); 46 int end = Math.min(COUNT, startPosition + loadCount); 47 int bgColor = COLORS[mGenerationId % COLORS.length]; 48 49 try { 50 Thread.sleep(1000); 51 } catch (InterruptedException e) { 52 e.printStackTrace(); 53 } 54 for (int i = startPosition; i != end; i++) { 55 items.add(new Item(i, "item " + i, bgColor)); 56 } 57 return items; 58 } 59 60 @Override 61 public void loadInitial(@NonNull LoadInitialParams params, 62 @NonNull LoadInitialCallback<Item> callback) { 63 int position = computeInitialLoadPosition(params, COUNT); 64 int loadSize = computeInitialLoadSize(params, position, COUNT); 65 List<Item> data = loadRangeInternal(position, loadSize); 66 callback.onResult(data, position, COUNT); 67 } 68 69 @Override 70 public void loadRange(@NonNull LoadRangeParams params, 71 @NonNull LoadRangeCallback<Item> callback) { 72 List<Item> data = loadRangeInternal(params.startPosition, params.loadSize); 73 callback.onResult(data); 74 } 75} 76