Skip to content

Instantly share code, notes, and snippets.

@ajailani4
Created June 3, 2021 11:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ajailani4/86629e0b2f697e06ae7e224e9e3d7e78 to your computer and use it in GitHub Desktop.
Save ajailani4/86629e0b2f697e06ae7e224e9e3d7e78 to your computer and use it in GitHub Desktop.
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