Created
June 16, 2019 14:32
-
-
Save enginebai/c6e6bdd3260038389ad579971aaf6f88 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 PostBoundaryCallback : PagedList.BoundaryCallback<Post>(), KoinComponent { | |
private val remoteDataSource: PostApiService by inject() | |
private val localDataSource: PostDao by inject() | |
private val httpClient: OkHttpClient by inject() | |
private val gson: Gson by inject() | |
private var nextPageUrl: String? = null | |
override fun onZeroItemsLoaded() { | |
super.onZeroItemsLoaded() | |
val response = remoteDataSource.getFeed().execute() | |
if (response.isSuccessful) { | |
nextPageUrl = parseNextPageUrl(response.headers()) | |
val postList: List<Post> = response.body() | |
upsertPostList(postList) | |
} | |
} | |
override fun onItemAtEndLoaded(itemAtEnd: MessageModel) { | |
super.onItemAtEndLoaded(itemAtEnd) | |
nextPageUrl?.run { | |
val response = httpClient.newCall( | |
Request.Builder() | |
.url(this) | |
.build() | |
).execute() | |
if (response.isSuccessful) { | |
nextPageUrl = parseNextPageUrl(response.headers()) | |
val listType = object : TypeToken<List<Post>>() {}.type | |
val postList: List<Post> = gson.fromJson(response.body()?.string(), listType) | |
upsertPostList(postList) | |
} | |
} | |
} | |
private fun upsertPostList(postList: List<Post>) { | |
postList.forEach { post -> | |
localDataSource.upsert(post) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment