Skip to content

Instantly share code, notes, and snippets.

@rohitjakhar
Created March 28, 2021 22:41
Show Gist options
  • Save rohitjakhar/68710d2b605cf26ac930e00d2f0e5e33 to your computer and use it in GitHub Desktop.
Save rohitjakhar/68710d2b605cf26ac930e00d2f0e5e33 to your computer and use it in GitHub Desktop.
PostDataSource
package com.rohitjakhar.blogx.repository
import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.rohitjakhar.blogx.model.PostData
import com.rohitjakhar.blogx.repository.remote.RemoteDataSource
class PostDataSource(private val remoteDataSource: RemoteDataSource) :
PagingSource<Int, PostData>() {
override fun getRefreshKey(state: PagingState<Int, PostData>): Int? {
TODO("Not yet implemented")
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, PostData> {
try {
val currentLoadingKey = params.key ?: 1
val response = remoteDataSource.apicall().getPost(currentLoadingKey)
val responseData = mutableListOf<PostData>()
val data = response.body() ?: arrayListOf()
responseData.addAll(data)
val prevKey = if (currentLoadingKey == 1) null else currentLoadingKey - 1
return LoadResult.Page(
data = responseData,
prevKey = prevKey,
nextKey = currentLoadingKey.plus(1)
)
} catch (e: Exception) {
return LoadResult.Error(e)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment