1 /* 2 * Copyright 2019 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 17 package androidx.paging 18 19 import androidx.paging.PagingSource.LoadResult.Error 20 import androidx.paging.PagingSource.LoadResult.Page 21 import androidx.testutils.DirectDispatcher 22 import kotlinx.coroutines.DelicateCoroutinesApi 23 import kotlinx.coroutines.GlobalScope 24 import kotlinx.coroutines.runBlocking 25 26 private class FakeSource<Value : Any>( 27 private val leadingNulls: Int, 28 private val trailingNulls: Int, 29 private val data: List<Value> 30 ) : PagingSource<Any, Value>() { loadnull31 override suspend fun load(params: LoadParams<Any>): LoadResult<Any, Value> { 32 if (params is LoadParams.Refresh) { 33 return Page( 34 data = data, 35 prevKey = null, 36 nextKey = null, 37 itemsBefore = leadingNulls, 38 itemsAfter = trailingNulls 39 ) 40 } 41 // TODO: prevent null-key load start/end 42 return Error(IllegalArgumentException("This test source only supports initial load")) 43 } 44 getRefreshKeynull45 override fun getRefreshKey(state: PagingState<Any, Value>): Any? = null 46 } 47 48 @OptIn(DelicateCoroutinesApi::class) 49 @Suppress("TestFunctionName", "DEPRECATION") 50 fun StringPagedList( 51 leadingNulls: Int, 52 trailingNulls: Int, 53 vararg items: String 54 ): PagedList<String> = runBlocking { 55 PagedList.create( 56 initialPage = 57 Page<Any, String>( 58 data = items.toList(), 59 prevKey = null, 60 nextKey = null, 61 itemsBefore = leadingNulls, 62 itemsAfter = trailingNulls 63 ), 64 pagingSource = FakeSource(leadingNulls, trailingNulls, items.toList()), 65 coroutineScope = GlobalScope, 66 notifyDispatcher = DirectDispatcher, 67 fetchDispatcher = DirectDispatcher, 68 boundaryCallback = null, 69 config = Config(1, prefetchDistance = 0), 70 key = null 71 ) 72 } 73