Skip to content

Instantly share code, notes, and snippets.

@enginebai
Created April 21, 2019 02:45
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 enginebai/8720c864583377dee870d9a23765b46a to your computer and use it in GitHub Desktop.
Save enginebai/8720c864583377dee870d9a23765b46a to your computer and use it in GitHub Desktop.
class PostPagingDataSource : PageKeyedDataSource<String, Post>(), KoinComponent {
private val api: PostApiService by inject()
private val httpClient: OkHttpClient by inject()
private val gson: Gson by inject()
override fun loadInitial(
params: LoadInitialParams<String>,
callback: LoadInitialCallback<String, Post>
) {
val response = api.getFeed().execute()
if (response.isSuccessful) {
val nextPageUrl = parseNextPageUrl(response.headers())
val postList = response.body().body()
callback.onResult(postList, null, nextPageUrl)
} else {
// TODO: error handling
}
}
override fun loadAfter(params: LoadParams<String>, callback: LoadCallback<String, Post>) {
val url = params.key
if (url.isNotEmpty()) {
val response = httpClient.newCall(
Request.Builder()
.url(url)
.build()
).execute()
if (response.isSuccessful) {
val nextPageUrl = parseNextPageUrl(response.headers())
val listType = object : TypeToken<List<Post>>() {}.type
val postList: List<Post> = gson.fromJson(response.body()?.string(), listType)
callback.onResult(postList, nextPageUrl)
}
}
}
override fun loadBefore(params: LoadParams<String>, callback: LoadCallback<String, Post>) {
// we don't need it, leave it empty
}
private fun parseNextPageUrl(headers: Headers): String? {
// parse URL from link header
}
}
class PostPagingDataSourceFactory : DataSource.Factory<String, Post>() {
override fun create(): DataSource<String, Post> {
return PostPagingDataSource()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment