Advertisement
Guest User

Untitled

a guest
Sep 17th, 2019
123
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. /**
  2. * Data source for lego sets pagination via paging library
  3. */
  4. class LegoSetPageDataSource @Inject constructor(
  5. private val themeId: Int? = null,
  6. private val dataSource: LegoSetRemoteDataSource,
  7. private val dao: LegoSetDao,
  8. private val scope: CoroutineScope) : PageKeyedDataSource<Int, LegoSet>() {
  9.  
  10. override fun loadInitial(params: LoadInitialParams<Int>, callback: LoadInitialCallback<Int, LegoSet>) {
  11. fetchData(1, params.requestedLoadSize) {
  12. callback.onResult(it, null, 2)
  13. }
  14. }
  15.  
  16. override fun loadAfter(params: LoadParams<Int>, callback: LoadCallback<Int, LegoSet>) {
  17. val page = params.key
  18. fetchData(page, params.requestedLoadSize) {
  19. callback.onResult(it, page + 1)
  20. }
  21. }
  22.  
  23. override fun loadBefore(params: LoadParams<Int>, callback: LoadCallback<Int, LegoSet>) {
  24. val page = params.key
  25. fetchData(page, params.requestedLoadSize) {
  26. callback.onResult(it, page - 1)
  27. }
  28. }
  29.  
  30. private fun fetchData(page: Int, pageSize: Int, callback: (List<LegoSet>) -> Unit) {
  31. scope.launch(getJobErrorHandler()) {
  32. val response = dataSource.fetchSets(page, pageSize, themeId)
  33. if (response.status == Result.Status.SUCCESS) {
  34. val results = response.data!!.results
  35. dao.insertAll(results)
  36. callback(results)
  37. } else if (response.status == Result.Status.ERROR) {
  38. postError(response.message!!)
  39. }
  40. }
  41. }
  42.  
  43. private fun getJobErrorHandler() = CoroutineExceptionHandler { _, e ->
  44. postError(e.message ?: e.toString())
  45. }
  46.  
  47. private fun postError(message: String) {
  48. Timber.e("An error happened: $message")
  49. }
  50.  
  51. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement