I want to merge two message list(stored chat message, incoming chat message)
these two data is split based on the last check time.
I want stored chat message to be Paging and merge with incoming data
This is my code:
#Query("SELECT * FROM msgentity WHERE room_id =:roomId and time <= :lastReadTime ORDER BY time")
fun getPassedMsg(roomId: String, lastReadTime: Date) : PagingSource<Int, MsgEntity>
#Query("SELECT * FROM msgentity WHERE room_id=:roomId and time > :lastReadTime ORDER BY time")
suspend fun getNewMsg(roomId: String, lastReadTime: Date) : Flow<List<MsgEntity>>
Is it possible to merge these two items of data?
Or do I have to make my own paging object?
Yeah definitely, you can show messages using paging.
if your question is that how ?
So here I am using MVVM architecture , Kotlin coroutine
Step 1. you need to create a paging source for request and getting response
(here MessageList is api response model )
class MessagePaging(private val apiService: ApiService) : PagingSource<Int, MessageList.Data>() {
private var STARTING_PAGE_INDEX = 1
override fun getRefreshKey(state: PagingState<Int, MessageList.Data>): Int? {
return 1
}
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MessageList.Data> {
val page = params.key ?: STARTING_PAGE_INDEX
return try {
val response = apiService.getMessageList(page)
val data = response.body()?.data!!
if (!data.isNullOrEmpty()){
LoadResult.Page(
data = data,
prevKey = if (page == STARTING_PAGE_INDEX) null else page -1,
nextKey = if (data.isEmpty()) null else page + 1
)
}else{
return LoadResult.Error(NullPointerException("Data is Null or Empty"))
}
} catch (e : HttpException){
return LoadResult.Error(e)
} catch (e : IOException){
return LoadResult.Error(e)
} catch (e : Exception){
return LoadResult.Error(e)
}
}
}
Step 2 :- Create request in apiservice
#GET( GET_CONSULTATION_LIST )
suspend fun getMessageList(#Query("page") page : Int) : Response<MessageList>
Step 3:- in ApiHelperImpl interface
fun getConsultationList(): Flow<PagingData<ConsultationList.Data>> {
return Pager(
config = PagingConfig(
pageSize = 40,
enablePlaceholders = false,
prefetchDistance = 1
),
pagingSourceFactory = { ConsultantPaging(apiService) }
).flow
}
Step 4 :- In View model
fun getConsultationList() = apiHelper.getConsultationList().cachedIn(viewModelScope)
Step 5 :- In Fragment
private fun observeConsultations() {
lifecycleScope.launch {
viewModel.getConsultationList().collectLatest {
launch(Dispatchers.Main) {
adapter.loadStateFlow.collectLatest { loadStates ->
if (loadStates.refresh is LoadState.Loading) {
// loader.show()
} else {
// loader.dismiss()
if (loadStates.refresh is LoadState.Error) {
if (adapter.itemCount < 1) {
binding.clNoConsult.visibility = View.VISIBLE
} else {
binding.clNoConsult.visibility = View.GONE
}
}
}
}
}
adapter.submitData(it)
}
}
}
Step 6:- Create Paging Adapter
class ConsultationPagingAdapter (private val click: GetClicksOnItem ) : PagingDataAdapter<MessageList.Data, ConsultationPagingAdapter.ViewHolder>(DiffCallback()) {
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
return ViewHolder(ListConsultationsBinding.inflate(LayoutInflater.from(parent.context), parent, false))
}
#SuppressLint("SetTextI18n")
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val result = getItem(position)!!
holder.binding.apply {
tvName.text = result.name.capitalizeWords()
root.setOnClickListener {
click.action(result)
}
executePendingBindings()
}
}
class ViewHolder(val binding: ListConsultationsBinding) : RecyclerView.ViewHolder(binding.root)
private class DiffCallback : DiffUtil.ItemCallback<MessageList.Data>() {
override fun areItemsTheSame(
oldItem: MessageList.Data,
newItem: MessageList.Data
): Boolean = oldItem == newItem
override fun areContentsTheSame(
oldItem: MessageList.Data,
newItem: MessageList.Data
): Boolean = oldItem == newItem
}
interface GetClicksOnItem {
fun action(data: MessageList.Data)
}
}
If you getting understating then approve the answer
Hello Guys im using Android Jetpack Paging library 3, I'm creating a news app that implements network + database scenario, and im following the codelab by google https://codelabs.developers.google.com/codelabs/android-paging , im doing it almost like in the codelab i almost matched all the operations shown in the examples https://github.com/android/architecture-components-samples/tree/main/PagingWithNetworkSample.
It works almost as it should...but my backend response is page keyed, i mean response comes with the list of news and the next page url, remote mediator fetches the data, populates the database, repository is set, viewmodel is set...
The problem is :
when recyclerview loads the data , following happens:recyclerview flickers, items jump, are removed , added again and so on.
I dont know why recyclerview or its itemanimator behaves like that , that looks so ugly and glitchy.
More than that, when i scroll to the end of the list new items are fetched and that glitchy and jumping effect is happening again.
I would be very grateful if you could help me, im sitting on it for three days , thank you very much in advance.Here are my code snippets:
#Entity(tableName = "blogs")
data class Blog(
#PrimaryKey(autoGenerate = true)
val databaseid:Int,
#field:SerializedName("id")
val id: Int,
#field:SerializedName("title")
val title: String,
#field:SerializedName("image")
val image: String,
#field:SerializedName("date")
val date: String,
#field:SerializedName("share_link")
val shareLink: String,
#field:SerializedName("status")
val status: Int,
#field:SerializedName("url")
val url: String
) {
var categoryId: Int? = null
var tagId: Int? = null
}
Here's the DAO
#Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertAll(blogs: List<Blog>)
#Query("DELETE FROM blogs")
suspend fun deleteAllBlogs()
#Query("SELECT * FROM blogs WHERE categoryId= :categoryId ORDER BY id DESC")
fun getBlogsSourceUniversal(categoryId:Int?): PagingSource<Int, Blog>
#Query("SELECT * FROM blogs WHERE categoryId= :categoryId AND tagId= :tagId ORDER BY id DESC")
fun getBlogsSourceUniversalWithTags(categoryId:Int?,tagId:Int?): PagingSource<Int, Blog>
NewsDatabaseKt
abstract class NewsDatabaseKt : RoomDatabase() {
abstract fun articleDAOKt(): ArticleDAOKt
abstract fun remoteKeyDao(): RemoteKeyDao
companion object {
#Volatile
private var INSTANCE: NewsDatabaseKt? = null
fun getDatabase(context: Context): NewsDatabaseKt =
INSTANCE ?: synchronized(this) {
INSTANCE ?: buildDatabase(context).also { INSTANCE = it }
}
private fun buildDatabase(context: Context) =
Room.databaseBuilder(context.applicationContext,
NewsDatabaseKt::class.java,
"news_database_kt")
.build()
}
RemoteMediator
#ExperimentalPagingApi
class BlogsRemoteMediator(private val categoryId: Int,
private val service: NewsAPIInterfaceKt,
private val newsDatabase: NewsDatabaseKt,
private val tagId : Int? = null ,
private val initialPage:Int = 1
) : RemoteMediator<Int, Blog>() {
override suspend fun initialize(): InitializeAction {
return InitializeAction.LAUNCH_INITIAL_REFRESH
}
override suspend fun load(loadType: LoadType, state: PagingState<Int, Blog>): MediatorResult {
try {
val page = when (loadType) {
REFRESH ->{
initialPage
}
PREPEND -> {
return MediatorResult.Success(endOfPaginationReached = true)}
APPEND -> {
val remoteKey = newsDatabase.withTransaction {
newsDatabase.remoteKeyDao().remoteKeyByLatest(categoryId.toString())
}
if(remoteKey.nextPageKey == null){
return MediatorResult.Success(endOfPaginationReached = true)
}
remoteKey.nextPageKey.toInt()
}
}
val apiResponse =
if(tagId == null) {
service.getCategoryResponsePage(RU, categoryId, page.toString())
}else{
service.getCategoryTagResponsePage(RU,categoryId,tagId,page.toString())
}
val blogs = apiResponse.blogs
val endOfPaginationReached = blogs.size < state.config.pageSize
newsDatabase.withTransaction {
// clear all tables in the database
if (loadType == LoadType.REFRESH) {
newsDatabase.remoteKeyDao().deleteByLatest(categoryId.toString())
if(tagId == null) {
newsDatabase.articleDAOKt().clearBlogsByCatId(categoryId)
}else {
newsDatabase.articleDAOKt().clearBlogsByCatId(categoryId,tagId)
}
}
blogs.map {blog ->
blog.categoryId = categoryId
if(tagId != null) {
blog.tagId = tagId
}
}
newsDatabase.remoteKeyDao().insert(LatestRemoteKey(categoryId.toString(),
apiResponse.nextPageParam))
newsDatabase.articleDAOKt().insertAll(blogs)
}
return MediatorResult.Success(
endOfPaginationReached = endOfPaginationReached
)
} catch (exception: IOException) {
return MediatorResult.Error(exception)
} catch (exception: HttpException) {
return MediatorResult.Error(exception)
}
}
PagingRepository
class PagingRepository(
private val service: NewsAPIInterfaceKt,
private val databaseKt: NewsDatabaseKt
){
#ExperimentalPagingApi
fun getBlogsResultStreamUniversal(int: Int, tagId : Int? = null) : Flow<PagingData<Blog>>{
val pagingSourceFactory = {
if(tagId == null) {
databaseKt.articleDAOKt().getBlogsSourceUniversal(int)
}else databaseKt.articleDAOKt().getBlogsSourceUniversalWithTags(int,tagId)
}
return Pager(
config = PagingConfig(
pageSize = 1
)
,remoteMediator =
BlogsRemoteMediator(int, service, databaseKt,tagId)
,pagingSourceFactory = pagingSourceFactory
).flow
}
}
BlogsViewmodel
class BlogsViewModel(private val repository: PagingRepository):ViewModel(){
private var currentResultUiModel: Flow<PagingData<UiModel.BlogModel>>? = null
private var categoryId:Int?=null
#ExperimentalPagingApi
fun getBlogsUniversalWithUiModel(int: Int, tagId : Int? = null):
Flow<PagingData<UiModel.BlogModel>> {
val lastResult = currentResultUiModel
if(lastResult != null && int == categoryId){
return lastResult
}
val newResult: Flow<PagingData<UiModel.BlogModel>> =
repository.getBlogsResultStreamUniversal(int, tagId)
.map { pagingData -> pagingData.map { UiModel.BlogModel(it)}}
.cachedIn(viewModelScope)
currentResultUiModel = newResult
categoryId = int
return newResult
}
sealed class UiModel{
data class BlogModel(val blog: Blog) : UiModel()
}
PoliticsFragmentKotlin
#ExperimentalPagingApi
class PoliticsFragmentKotlin : Fragment() {
private lateinit var recyclerView: RecyclerView
private lateinit var pagedBlogsAdapter:BlogsAdapter
lateinit var viewModelKt: BlogsViewModel
lateinit var viewModel:NewsViewModel
private var searchJob: Job? = null
#ExperimentalPagingApi
private fun loadData(categoryId:Int, tagId : Int? = null) {
searchJob?.cancel()
searchJob = lifecycleScope.launch {
viewModelKt.getBlogsUniversalWithUiModel(categoryId, tagId).collectLatest {
pagedBlogsAdapter.submitData(it)
}
}
}
#ExperimentalPagingApi
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.fragment_blogs, container, false)
viewModelKt = ViewModelProvider(requireActivity(),Injection.provideViewModelFactory(requireContext())).get(BlogsViewModel::class.java)
viewModel = ViewModelProvider(requireActivity()).get(NewsViewModel::class.java)
pagedBlogsAdapter = BlogsAdapter(context,viewModel)
val decoration = DividerItemDecoration(context, DividerItemDecoration.VERTICAL)
recyclerView = view.findViewById(R.id.politics_recyclerView)
recyclerView.addItemDecoration(decoration)
initAdapter()
loadData(categoryId)
initLoad()
return view
}
private fun initLoad() {
lifecycleScope.launchWhenCreated {
Log.d("meylis", "lqunched loadstate scope")
pagedBlogsAdapter.loadStateFlow
// Only emit when REFRESH LoadState for RemoteMediator changes.
.distinctUntilChangedBy { it.refresh }
// Only react to cases where Remote REFRESH completes i.e., NotLoading.
.filter { it.refresh is LoadState.NotLoading }
.collect { recyclerView.scrollToPosition(0) }
}
}
private fun initAdapter() {
recyclerView.adapter = pagedBlogsAdapter.withLoadStateHeaderAndFooter(
header = BlogsLoadStateAdapter { pagedBlogsAdapter.retry() },
footer = BlogsLoadStateAdapter { pagedBlogsAdapter.retry() }
)
lifecycleScope.launchWhenCreated {
pagedBlogsAdapter.loadStateFlow.collectLatest {
swipeRefreshLayout.isRefreshing = it.refresh is LoadState.Loading
}
}
pagedBlogsAdapter.addLoadStateListener { loadState ->
// Only show the list if refresh succeeds.
recyclerView.isVisible = loadState.source.refresh is LoadState.NotLoading
// Show loading spinner during initial load or refresh.
progressBar.isVisible = loadState.source.refresh is LoadState.Loading
// Show the retry state if initial load or refresh fails.
retryButton.isVisible = loadState.source.refresh is LoadState.Error
// Toast on any error, regardless of whether it came from RemoteMediator or PagingSource
val errorState = loadState.source.append as? LoadState.Error
?: loadState.source.prepend as? LoadState.Error
?: loadState.append as? LoadState.Error
?: loadState.prepend as? LoadState.Error
errorState?.let {
Toast.makeText(context, "\uD83D\uDE28 Wooops ${it.error}", Toast.LENGTH_LONG
).show()
}
}
}
companion object {
#JvmStatic
fun newInstance(categoryId: Int, tags : ArrayList<Tag>): PoliticsFragmentKotlin {
val args = Bundle()
args.putInt(URL, categoryId)
args.putSerializable(TAGS,tags)
val fragmentKotlin = PoliticsFragmentKotlin()
fragmentKotlin.arguments = args
Log.d("meylis", "created instance")
return fragmentKotlin
}
}
BlogsAdapter
class BlogsAdapter(var context: Context?, var newsViewModel:NewsViewModel) :
PagingDataAdapter<BlogsViewModel.UiModel.BlogModel, RecyclerView.ViewHolder>
(REPO_COMPARATOR) {
private val VIEW = 10
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
return when (viewType) {
VIEW -> MyViewHolder(LayoutInflater.from(parent.context).inflate(R.layout.card_layout, parent, false))
}
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
val uiModel = getItem(position)
if(uiModel == null){
if(uiModel is BlogsViewModel.UiModel.BlogModel){(holder as MyViewHolder).bind(null)}
}
if(uiModel is BlogsViewModel.UiModel.BlogModel){(holder as
MyViewHolder).bind(uiModel.blog)}
}
override fun getItemViewType(position: Int): Int {
return VIEW
}
companion object {
private val REPO_COMPARATOR = object : DiffUtil.ItemCallback<BlogsViewModel.UiModel.BlogModel>() {
override fun areItemsTheSame(oldItem: BlogsViewModel.UiModel.BlogModel, newItem: BlogsViewModel.UiModel.BlogModel): Boolean =
oldItem.blog.title == newItem.blog.title
override fun areContentsTheSame(oldItem: BlogsViewModel.UiModel.BlogModel, newItem: BlogsViewModel.UiModel.BlogModel): Boolean =
oldItem == newItem
}
}
MyViewHolder
class MyViewHolder(var container: View) : RecyclerView.ViewHolder(container) {
var cv: CardView
#JvmField
var mArticle: TextView
var date: TextView? = null
#JvmField
var time: TextView
#JvmField
var articleImg: ImageView
#JvmField
var shareView: View
var button: MaterialButton? = null
#JvmField
var checkBox: CheckBox
var progressBar: ProgressBar
private var blog:Blog? = null
init {
cv = container.findViewById<View>(R.id.cardvmain) as CardView
mArticle = container.findViewById<View>(R.id.article) as TextView
articleImg = container.findViewById<View>(R.id.imgvmain) as ImageView
//button = (MaterialButton) itemView.findViewById(R.id.sharemain);
checkBox = container.findViewById<View>(R.id.checkboxmain) as CheckBox
time = container.findViewById(R.id.card_time)
shareView = container.findViewById(R.id.shareView)
progressBar = container.findViewById(R.id.blog_progress)
}
fun bind(blog: Blog?){
if(blog == null){
mArticle.text = "loading"
time.text = "loading"
articleImg.visibility = View.GONE
}else {
this.blog = blog
mArticle.text = blog.title
time.text = blog.date
if (blog.image.startsWith("http")) {
articleImg.visibility = View.VISIBLE
val options: RequestOptions = RequestOptions()
.centerCrop()
.priority(Priority.HIGH)
GlideImageLoader(articleImg,
progressBar).load(blog.image, options)
} else {
articleImg.visibility = View.GONE
}
}
}
}
NewsApiInterface
interface NewsAPIInterfaceKt {
#GET("sort?")
suspend fun getCategoryResponsePage(#Header("Language") language: String, #Query("category")
categoryId: Int, #Query("page") pageNumber: String): BlogsResponse
#GET("sort?")
suspend fun getCategoryTagResponsePage(#Header("Language") language: String,
#Query("category") categoryId: Int,#Query("tag") tagId:Int, #Query("page") pageNumber: String)
:BlogsResponse
companion object {
fun create(): NewsAPIInterfaceKt {
val logger = HttpLoggingInterceptor()
logger.level = HttpLoggingInterceptor.Level.BASIC
val okHttpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient()
return Retrofit.Builder()
.baseUrl(BASE_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build()
.create(NewsAPIInterfaceKt::class.java)
}
}
}
I have tried setting initialLoadSize = 1
But the problem still persists
EDIT: Thanks for your answer #dlam , yes, it does , my network API returns the list of results ordered by id. BTW, items do this jump when the application is run offline as well.
Videos when refreshing and loading online
online loading and paging
online loading and paging(2)
Videos when refreshing and loading offline
offline loading and refreshing
Thanks again, here is my gist link https://gist.github.com/Aydogdyshka/7ca3eb654adb91477a42128de2f06ea9
EDIT
Thanks a lot to #dlam, when I set pageSize=10, jumping has disappeared...Then i remembered why i set pageSize=1 in the first place... when i refresh , 3 x pageSize of items are loaded, even if i overrided initialLoadSize = 10 , it still loads 3 x pageSize calling append 2x times after refresh , what could i be doing wrong, what's the correct way to only load first page when i refresh ?
Just following up here from comments:
Setting pageSize = 10 fixes the issue.
The issue was with pageSize being too small, resulting in PagingSource refreshes loading pages that did not cover the viewport. Since source refresh replaces the list and goes through DiffUtil, you need to provide an initialLoadSize that is large enough so that there is some overlap (otherwise scroll position will be lost).
BTW - Paging loads additional data automatically based on PagingConfig.prefetchDistance. If RecyclerView binds items close enough to the edge of the list, it will automatically trigger APPEND / PREPEND loads. This is why the default of initialLoadSize is 3 * pageSize, but if you're still experiencing additional loads, I would suggest either adjusting prefetchDistance, or increasing initialLoadSize further.
config = PagingConfig(
pageSize = PAGE_SIZE,
enablePlaceholders = true,
prefetchDistance = 3* PAGE_SIZE,
initialLoadSize = 2*PAGE_SIZE,
)
make sure enablePlaceholders is set to true and set the page size to around 10 to 20
recyclerview flickers becouse from dao you get items not the same order it was responded from network.
I will suggest you my solution.
we will get items from database order by primary key, databaseid, descending.
first of all delete autogenerated = true.
we will set databaseid manualy, in same order we got items from network.
next lets edit remoteMediator load function.
when (loadType) {
LoadType.PREPEND -> {
blogs.map {
val databaseid = getFirstBlogDatabaseId(state)?.databaseid?:0
movies.forEachIndexed{
index, blog ->
blog.databaseid = roomId - (movies.size -index.toLong())
}
}
}
LoadType.APPEND -> {
val roomId = getLastBlogDatabaseId(state)?.databaseid ?:0
blogs.forEachIndexed{
index, blog ->
blog.databaseid = roomId + index.toLong() + 1
}
}
LoadType.REFRESH -> {
blogs.forEachIndexed{
index, blog ->
blog.databaseid = index.toLong()
}
}
}
private fun getFirstBlogDatabaseId(state: PagingState<Int, Blog>): Blog? {
return state.pages.firstOrNull { it.data.isNotEmpty() }?.data?.firstOrNull()
}
private fun getLastBlogDatabaseId(state: PagingState<Int, Blog>): Blog? {
return state.lastItemOrNull()
}
I am trying to use android Paging 3 (version 3.0.0-SNAPSHOT) for paging data from Room database(no remote data source).
Initially the page loads data successfully , but when a new "Entry" is added to database and I return to this page,collectLatest is fired but no data is loaded ("pagingData" entry list is empty )
this is my query :
#Query("SELECT * FROM entry ORDER BY dateTime DESC")
fun getAll() : PagingSource<Int, Entry>
and this is my viewmodel:
val flow = Pager(
PagingConfig(pageSize = 20)
) {
entryDao.getAll()
}.flow
.cachedIn(viewModelScope)
in my fragment , I am observing the data like this :
iewLifecycleOwner.lifecycleScope.launch {
homeViewModel.flow.collectLatest { pagingData ->
adapter.submitData(pagingData)
}
}
and this is my adapter:
class EntriesAdapter( val context : Context, private val onClick: (String)->Unit) :
PagingDataAdapter<Entry , RecyclerView.ViewHolder>(diffCallback)
{
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): EntryViewHolder
= EntryViewHolder(
DataBindingUtil.inflate(
LayoutInflater.from(parent.context),
R.layout.item_entry, parent, false
) , onClick)
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
var entry = getItem(position)
if (entry != null) {
(holder as EntryViewHolder).bindTo(entry);
}
}
companion object {
//This diff callback informs the PagedListAdapter how to compute list differences when new
private val diffCallback = object : DiffUtil.ItemCallback<Entry>() {
override fun areItemsTheSame(oldItem: Entry, newItem: Entry): Boolean =
oldItem.id == newItem.id
override fun areContentsTheSame(oldItem: Entry, newItem: Entry): Boolean =
oldItem.id == newItem.id
}
}
inner class EntryViewHolder( val binding : ItemEntryBinding ,val onCLick:
(String)->Unit ) : RecyclerView.ViewHolder(binding.root) {
var entry:Entry? = null
fun bindTo(entry: Entry) {
this.entry = entry
with(binding) {
entryItem = entry
cardView.setOnClickListener{
onCLick
}
executePendingBindings()
}
}
}
}
I had a similar problem to yours and I just forgot to call entriesAdapter.refresh() after add new item.
In fact, I am trying to migrate from paging 2 to paging 3. Already I have successfully implemented PageKeyedDataSource of Paging 2 with RxpagingSource in my codebase. But when I tried to implement ItemKeyedDataSource of Paging 2 to Paging library 3, I got confused to implement that. I also tried to code. but got stuck. Here is my code.
JobSliderRestApi.kt
#GET("job/list/slides")
fun getDetailOfSelectedJob(
#Query("current_job") currentJodId: Int?,
#Query("limit") jobLimit: Int?,
#Query("search_in") fetchType: String?
): Single<Response<JobViewResponse>>
JobViewResponse.kt
data class JobViewResponse(
#SerializedName("data") val data: ArrayList<JobDetail>?
) : BaseResponse()
JodSliderDataSource.kt
class JodSliderDataSource #Inject constructor(
private val jobSliderRestApi: JobSliderRestApi,
private val currentJobId: Int
): RxPagingSource<Int, JobDetail>() {
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, JobDetail>> {
return jobSliderRestApi.getDetailOfSelectedJob(currentJobId, 20, "next").toSingle()
.subscribeOn(Schedulers.io())
.map { jobResponse -> jobResponse.data }
.map { jobData -> toLoadResult(jobData, position) } // Don't know what to do
.onErrorReturn { LoadResult.Error(it) }
}
//Don't know what to do
private fun toLoadResult(data: JobDetail, position: Int): LoadResult<Int, JobDetail> {
/**val prevKey = if (position == 1) null else position-1
val nextKey = if (data.hasMore) position+1 else null
return LoadResult.Page(data.jobs, prevKey, nextKey)*/
}
#ExperimentalPagingApi
override fun getRefreshKey(state: PagingState<Int, JobDetail>): Int? {
return super.getRefreshKey(state)
}
}
in fact, previously I used 'currentJodId' to differentiate list in Paging 2. but in paging 3, I did not get any clue t fix these
After a lot of searching I solved the problem. Here is the updated JodSliderDataSource class
class JodSliderDataSource #Inject constructor(
private val jobSliderRestApi: JobSliderRestApi
): RxPagingSource<Int, JobDetail>() {
override val keyReuseSupported = true
#ExperimentalPagingApi
override fun getRefreshKey(state: PagingState<Int, JobDetail>): Int? {
return state.anchorPosition?.let {
state.closestItemToPosition(it)?.jobId
}
}
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, JobDetail>> {
return jobSliderRestApi.getDetailOfSelectedJob(42673, 2, "next").toSingle()
.subscribeOn(Schedulers.io())
.map { jobResponse -> toLoadResult(jobResponse.data) }
.onErrorReturn { LoadResult.Error(it) }
}
private fun toLoadResult(data: ArrayList<JobDetail>): LoadResult<Int, JobDetail> {
return LoadResult.Page(data = data, prevKey = null, nextKey = data.lastOrNull()?.jobId)
}
}
I want to implement pagination to show a chunk of list of my desire item view in my app. That's why I choose to use Google newly released paging library i.e Paging library 3. I use Rxjava, Livedata, and ViewModel in my app.
After implementing the paging library, I am facing a weird problem. When I call the method for fetching list, it's calling again and again and not stopped calling the call. In fact, it automatically increases the page number although I did not scroll the list.
Here is the code I tried
JobListRestApi.kt
interface JobListRestApi {
#GET("job/list")
fun getJobResponse(
#Query("page") pageNumber: Int
): Single<Response<JobResponse>>
}
JobListDataSource.kt
class JobListDataSource #Inject constructor(
private val jobListRestApi: JobListRestApi
): RxPagingSource<Int, Job>() {
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, Job>> {
val position = params.key ?: 1
return jobListRestApi.getJobResponse(position).toSingle()
.subscribeOn(Schedulers.io())
.map { jobResponse -> jobResponse.jobData.jobs }
.map { jobs -> toLoadResult(jobs, position) }
.onErrorReturn { LoadResult.Error(it) }
}
private fun toLoadResult(data: ArrayList<Job>, position: Int): LoadResult<Int, Job> {
val prevKey = if (position == 1) null else position-1
val nextKey = if (position == data.size) null else position+1
return LoadResult.Page(data, prevKey, nextKey)
}
}
JobListRepositoryImpl.kt
class JobListRepositoryImpl #Inject constructor(
private val jobListDataSource: JobListDataSource
): JobListRepository {
override fun getJobs(): Flowable<PagingData<Job>> {
return Pager(PagingConfig(pageSize = 20)) {
jobListDataSource
}.flowable
}
}
JobListViewModel.kt
class JobListViewModel #Inject constructor(
private val jobListRepository: JobListRepository
): BaseViewModel() {
val jobs: MutableLiveData<PagingData<Job>> = MutableLiveData()
fun getJobs() {
if (jobs.value == null) {
compositeDisposable += jobListRepository.getJobs()
.subscribe({
jobs.value = it
}, {
handleException(it)
})
}
}
}
JobListFragment.kt
class JobListFragment : BaseFragment<JobListViewModel>() {
private val jobAdapter: JobAdapter by lazy {
JobAdapter { }
}
override fun getLayoutResource() = R.layout.fragment_job_list
override fun initWidget() {
job_recycler_view.adapter = jobAdapter
}
override fun onResume() {
super.onResume()
viewModel.getJobs()
}
override fun observeLiveData() {
observe(viewModel.jobs) {
jobAdapter.submitData(lifecycle, it)
}
}
}
And the output log is
https://base-url/job/list?page=1
https://base-url/job/list?page=2
https://base-url/job/list?page=3
https://base-url/job/list?page=4
https://base-url/job/list?page=5
https://base-url/job/list?page=6
https://base-url/job/list?page=7
how can I stop calling serial api unless I go to the last item of the chunk in RecyclerView and scroll the list
You tell Paging there is no more to load by returning null for prevKey and nextKey inLoadResult.Page
Since its infinitely appending, it looks like you never set nextKey to null. Perhaps you meant to check data.isEmpty() instead of key == data.size?
Eventually, I got the error. In fact, the problem was in my Http response Data. The updated DataSource is given bellow
JobListDataSource.kt
class JobListDataSource #Inject constructor(
private val jobListRestApi: JobListRestApi
): RxPagingSource<Int, Job>() {
override fun loadSingle(params: LoadParams<Int>): Single<LoadResult<Int, Job>> {
val position = params.key ?: 1
return jobListRestApi.getJobResponse(position).toSingle()
.subscribeOn(Schedulers.io())
.map { jobResponse -> jobResponse.jobData }
.map { jobData -> toLoadResult(jobData, position) }
.onErrorReturn { LoadResult.Error(it) }
}
private fun toLoadResult(data: JobData, position: Int): LoadResult<Int, Job> {
val prevKey = if (position == 1) null else position-1
val nextKey = if (data.hasMore) position+1 else null
return LoadResult.Page(data.jobs, prevKey, nextKey)
}
}