Created
June 3, 2021 11:08
-
-
Save ajailani4/86629e0b2f697e06ae7e224e9e3d7e78 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class BrandsHomeDataSource @Inject constructor( | |
private val apiHelper: ApiHelper | |
) : PagingSource<Int, Brand>() { | |
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Brand> { | |
val currentLoadingPageKey = params.key ?: 1 | |
return try { | |
val response = apiHelper.getBrands(currentLoadingPageKey, 5) | |
val data = response.body()?.data?.brands ?: emptyList() | |
// Put phonesList to each brand | |
data.forEach { brand -> | |
brand.phonesList = apiHelper.getPhonesHome(brand.slug).body()?.data?.phones | |
?: emptyList() | |
} | |
val prevKey = if (currentLoadingPageKey == 1) null else currentLoadingPageKey - 1 | |
LoadResult.Page( | |
data = data, | |
prevKey = prevKey, | |
nextKey = currentLoadingPageKey.plus(1) | |
) | |
} catch (e: Exception) { | |
LoadResult.Error(e) | |
} | |
} | |
override fun getRefreshKey(state: PagingState<Int, Brand>): Int? { | |
return state.anchorPosition | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment