Created
April 21, 2019 02:45
-
-
Save enginebai/8720c864583377dee870d9a23765b46a to your computer and use it in GitHub Desktop.
This file contains hidden or 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 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