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