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() { companion object { private const val PAGE_SIZE = 30 } override suspend fun load(params: LoadParams): LoadResult { 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? { return state.anchorPosition } }