Last active
September 29, 2019 20:55
-
-
Save wangerekaharun/030c5f3eb85e8e16e5373042a535ccc5 to your computer and use it in GitHub Desktop.
Reddit Data Source Class
This file contains 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 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