Skip to content

Instantly share code, notes, and snippets.

@wangerekaharun
Last active September 29, 2019 20:55
Show Gist options
  • Save wangerekaharun/030c5f3eb85e8e16e5373042a535ccc5 to your computer and use it in GitHub Desktop.
Save wangerekaharun/030c5f3eb85e8e16e5373042a535ccc5 to your computer and use it in GitHub Desktop.
Reddit Data Source Class
class PostsDataSource(private val scope: CoroutineScope) :
PageKeyedDataSource<String, RedditPost>() {
private val apiService = ApiClient.getClient().create(ApiService::class.java)
override fun loadInitial(params: LoadInitialParams<String>, callback: LoadInitialCallback<String, RedditPost>) {
scope.launch {
try {
val response = apiService.fetchPosts(loadSize = params.requestedLoadSize)
when{
response.isSuccessful -> {
val listing = response.body()?.data
val redditPosts = listing?.children?.map { it.data }
callback.onResult(redditPosts ?: listOf(), listing?.before, listing?.after)
}
}
}catch (exception : Exception){
Log.e("PostsDataSource", "Failed to fetch data!")
}
}
}
override fun loadAfter(params: LoadParams<String>, callback: LoadCallback<String, RedditPost>) {
scope.launch {
try {
val response =
apiService.fetchPosts(loadSize = params.requestedLoadSize, after = params.key)
when{
response.isSuccessful -> {
val listing = response.body()?.data
val items = listing?.children?.map { it.data }
callback.onResult(items ?: listOf(), listing?.after)
}
}
}catch (exception : Exception){
Log.e("PostsDataSource", "Failed to fetch data!")
}
}
}
override fun loadBefore(params: LoadParams<String>, callback: LoadCallback<String, RedditPost>) {
scope.launch {
try {
val response =
apiService.fetchPosts(loadSize = params.requestedLoadSize, before = params.key)
when{
response.isSuccessful -> {
val listing = response.body()?.data
val items = listing?.children?.map { it.data }
callback.onResult(items ?: listOf(), listing?.after)
}
}
}catch (exception : Exception){
Log.e("PostsDataSource", "Failed to fetch data!")
}
}
}
override fun invalidate() {
super.invalidate()
scope.cancel()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment