Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.