Skip to content

Instantly share code, notes, and snippets.

@bltuckerdevblog
Last active May 27, 2018 17:56
Show Gist options
  • Save bltuckerdevblog/2ba5c22d462f73c5b8ba9217b549b76d to your computer and use it in GitHub Desktop.
Save bltuckerdevblog/2ba5c22d462f73c5b8ba9217b549b76d to your computer and use it in GitHub Desktop.
interface ProductsApi {
@GET("products")
fun searchProducts(@Query("searchTerm") searchTerm: String, @Query("page") page: Int) : Call<ProductsResponse>
@GET
fun getPageOfResults(@Url nextPageUrl: String) : Call<ProductsResponse>
}
class ProductsDataSource constructor(private val productsApi: ProductsApi,
private val searchTerm: String) : PageKeyedDataSource<String, Product>() {
override fun loadInitial(params: LoadInitialParams<String>, callback: LoadInitialCallback<String, Product>) {
val productsResponse = productsApi.searchProducts(searchTerm, 1).execute()
val nextPageUrl = productsResponse.body()?.meta?.nextPageUrl ?: null
val products = productsResponse.body()?.products ?: listOf()
callback.onResult(products, null, nextPageUrl)
}
override fun loadAfter(params: LoadParams<String>, callback: LoadCallback<String, Product>) {
val productsResponse = productsApi.getPageOfResults(params.key).execute()
val nextPageUrl = productsResponse.body()?.meta?.nextPageUrl ?: null
val products = productsResponse.body()?.products ?: listOf()
callback.onResult(products, nextPageUrl)
}
override fun loadBefore(params: LoadParams<String>, callback: LoadCallback<String, Product>) {
val productsResponse = productsApi.getPageOfResults(params.key).execute()
val nextPageUrl = productsResponse.body()?.meta?.nextPageUrl ?: null
val products = productsResponse.body()?.products ?: listOf()
callback.onResult(products, nextPageUrl)
}
}
class ProductsDataSourceFactory @Inject constructor(private val productsApi: ProductsApi,
private val searchTerm: String) : DataSource.Factory<String, Product>() {
override fun create(): DataSource<String, Product> {
return ProductsDataSource(productsApi, searchTerm)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment