Вторая часть по кэшу
This commit is contained in:
@@ -0,0 +1,43 @@
|
||||
package chats.data.local.paging
|
||||
|
||||
import androidx.paging.PagingSource
|
||||
import androidx.paging.PagingState
|
||||
import chats.data.local.dao.MessageDao
|
||||
import chats.data.local.database.MessageEntity
|
||||
|
||||
/**
|
||||
* PagingSource для загрузки сообщений из Room Database
|
||||
*/
|
||||
class MessagePagingSource(
|
||||
private val chatId: String,
|
||||
private val messageDao: MessageDao
|
||||
) : PagingSource<Int, MessageEntity>() {
|
||||
|
||||
companion object {
|
||||
private const val PAGE_SIZE = 30
|
||||
}
|
||||
|
||||
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, MessageEntity> {
|
||||
return try {
|
||||
val position = params.key ?: 0 // Начинаем с 0
|
||||
|
||||
val messages = messageDao.getMessagesPaged(
|
||||
chatId = chatId,
|
||||
offset = position,
|
||||
limit = PAGE_SIZE
|
||||
)
|
||||
|
||||
LoadResult.Page(
|
||||
data = messages,
|
||||
prevKey = if (position > 0) position - PAGE_SIZE else null,
|
||||
nextKey = if (messages.isEmpty()) null else position + PAGE_SIZE
|
||||
)
|
||||
} catch (e: Exception) {
|
||||
LoadResult.Error(e)
|
||||
}
|
||||
}
|
||||
|
||||
override fun getRefreshKey(state: PagingState<Int, MessageEntity>): Int? {
|
||||
return state.anchorPosition
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user