Проблема:
При внедрении пейджинга с библиотекой Paging3 я не могу заставить дистанционного факультета. Данные не извлекаются дальше, даже если EndofApaginationReach, неверно. Как будто я, например, устанавливаю PageSize на 10, я изначально приношу и сохраняю 20 элементов в базу данных, но затем мой PagingSource достигает до конца, и ничего не происходит.@OptIn(ExperimentalPagingApi::class)
class RemoteMediator(
private val api: Client,
private val dataSource: ServerDataSource,
private val remoteKeyDataSource: RemoteKeyDataSource
) : RemoteMediator() {
companion object {
private const val REMOTE_KEY_ID = "servers"
}
override suspend fun load(
loadType: LoadType,
state: PagingState
): MediatorResult {
val pageKey: String? = when (loadType) {
LoadType.REFRESH -> null
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> {
remoteKeyDataSource.findNextKey(REMOTE_KEY_ID)
}
}
// If appending but no next_key, we've reached the end
if (loadType == LoadType.APPEND && pageKey == null) {
return MediatorResult.Success(endOfPaginationReached = true)
}
return try {
// Call your client and skip the initial Loading emission
val result = api
.getServers(
size = state.config.pageSize,
sort = "rank",
key = pageKey
)
.filter { it !is Result.Loading }
.first()
val page = when (result) {
is Result.Success -> result.data
is Result.Error -> throw result.exception
else -> throw IllegalStateException("Unexpected result: $result")
}
val entities = page.data.map { it.toServerInfo() }
val nextKey = extractPageKey(page.links?.next)
val prevKey = extractPageKey(page.links?.prev)
Napier.i("loadType=$loadType, pageKey=$pageKey, API result: ${page.data.size}, nextKey=$nextKey", tag = "RemoteMediator")
// Persist within one transaction
if (loadType == LoadType.REFRESH) {
dataSource.clearNotFavouriteServers()
remoteKeyDataSource.clearRemoteKeys()
}
dataSource.upsertServers(entities)
remoteKeyDataSource.insertOrReplaceRemoteKey(
id = REMOTE_KEY_ID,
nextKey = nextKey,
prevKey = prevKey
)
Napier.i ("RemoteMediator: endOfPaginationReached:${nextKey == null && page.data.isEmpty()} ", tag = "RemoteMediator")
MediatorResult.Success(endOfPaginationReached = (nextKey == null && page.data.isEmpty()))
} catch (e: IOException) {
MediatorResult.Error(e)
} catch (e: Exception) {
MediatorResult.Error(e)
}
}
}
fun extractPageKey(url: String?): String? {
if (url == null) return null
val parsed = Url(url)
return parsed.parameters["page[key]"]
}
< /code>
class ServerPagingSource(
private val dataSource: ServerDataSource,
private val query: ServerQuery
) : PagingSource() {
companion object {
private const val REMOTE_KEY_ID = "servers"
}
override suspend fun load(params: LoadParams): LoadResult {
val offset = params.key ?: 0
return try {
val servers = dataSource.getPagedServers(query, params.loadSize.toLong(), offset.toLong())
Napier.i(message = "Loaded ${servers.size} servers with offset $offset", tag = "ServerPagingSource")
Napier.i(message = "limit is ${params.loadSize}", tag = "ServerPagingSource")
LoadResult.Page(
data = servers,
prevKey = if (offset == 0) null else offset - params.loadSize,
nextKey = if (servers.size < params.loadSize) null else offset + params.loadSize
)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState): Int? {
Napier.i(message = "getRefreshKey called with state: $state", tag = "ServerPagingSource")
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(state.config.pageSize)
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(state.config.pageSize)
}
}
}
< /code>
class GetPagedServersUseCase(
private val api: BattlemetricsClient,
private val dataSource: ServerDataSource,
private val remoteKeyDataSource: RemoteKeyDataSource
) {
@OptIn(ExperimentalPagingApi::class)
operator fun invoke(query: ServerQuery): Flow {
return Pager(
config = PagingConfig(
pageSize = 10,
enablePlaceholders = false
),
remoteMediator = BattlemetricsRemoteMediator(api, dataSource, remoteKeyDataSource),
pagingSourceFactory = { dataSource.getServersPagingSource(query) }
).flow
}
}
< /code>
Вот вывод журнала от удаленного среднего после запуска приложения и прокрутки вниз: < /p>
2025-06-16 17:06:32.729 31912-31912 RemoteMediator loadType=REFRESH, pageKey=null, API result: 10, nextKey=10,7459421
2025-06-16 17:06:32.857 31912-31912 RemoteMediator RemoteMediator: endOfPaginationReached:false
2025-06-16 17:06:33.687 31912-31912 RemoteMediator loadType=APPEND, pageKey=10,7459421, API result: 10, nextKey=20,26937093
2025-06-16 17:06:33.793 31912-31912 RemoteMediator RemoteMediator: endOfPaginationReached:false
Подробнее здесь: https://stackoverflow.com/questions/796 ... lazycolumn
Remotemediator не получает данные после прокрутки в Lazycolumn ⇐ Android
Форум для тех, кто программирует под Android
-
Anonymous
1750339405
Anonymous
[b] Проблема: [/b]
При внедрении пейджинга с библиотекой Paging3 я не могу заставить дистанционного факультета. Данные не извлекаются дальше, даже если EndofApaginationReach, неверно. Как будто я, например, устанавливаю PageSize на 10, я изначально приношу и сохраняю 20 элементов в базу данных, но затем мой PagingSource достигает до конца, и ничего не происходит.@OptIn(ExperimentalPagingApi::class)
class RemoteMediator(
private val api: Client,
private val dataSource: ServerDataSource,
private val remoteKeyDataSource: RemoteKeyDataSource
) : RemoteMediator() {
companion object {
private const val REMOTE_KEY_ID = "servers"
}
override suspend fun load(
loadType: LoadType,
state: PagingState
): MediatorResult {
val pageKey: String? = when (loadType) {
LoadType.REFRESH -> null
LoadType.PREPEND -> return MediatorResult.Success(endOfPaginationReached = true)
LoadType.APPEND -> {
remoteKeyDataSource.findNextKey(REMOTE_KEY_ID)
}
}
// If appending but no next_key, we've reached the end
if (loadType == LoadType.APPEND && pageKey == null) {
return MediatorResult.Success(endOfPaginationReached = true)
}
return try {
// Call your client and skip the initial Loading emission
val result = api
.getServers(
size = state.config.pageSize,
sort = "rank",
key = pageKey
)
.filter { it !is Result.Loading }
.first()
val page = when (result) {
is Result.Success -> result.data
is Result.Error -> throw result.exception
else -> throw IllegalStateException("Unexpected result: $result")
}
val entities = page.data.map { it.toServerInfo() }
val nextKey = extractPageKey(page.links?.next)
val prevKey = extractPageKey(page.links?.prev)
Napier.i("loadType=$loadType, pageKey=$pageKey, API result: ${page.data.size}, nextKey=$nextKey", tag = "RemoteMediator")
// Persist within one transaction
if (loadType == LoadType.REFRESH) {
dataSource.clearNotFavouriteServers()
remoteKeyDataSource.clearRemoteKeys()
}
dataSource.upsertServers(entities)
remoteKeyDataSource.insertOrReplaceRemoteKey(
id = REMOTE_KEY_ID,
nextKey = nextKey,
prevKey = prevKey
)
Napier.i ("RemoteMediator: endOfPaginationReached:${nextKey == null && page.data.isEmpty()} ", tag = "RemoteMediator")
MediatorResult.Success(endOfPaginationReached = (nextKey == null && page.data.isEmpty()))
} catch (e: IOException) {
MediatorResult.Error(e)
} catch (e: Exception) {
MediatorResult.Error(e)
}
}
}
fun extractPageKey(url: String?): String? {
if (url == null) return null
val parsed = Url(url)
return parsed.parameters["page[key]"]
}
< /code>
class ServerPagingSource(
private val dataSource: ServerDataSource,
private val query: ServerQuery
) : PagingSource() {
companion object {
private const val REMOTE_KEY_ID = "servers"
}
override suspend fun load(params: LoadParams): LoadResult {
val offset = params.key ?: 0
return try {
val servers = dataSource.getPagedServers(query, params.loadSize.toLong(), offset.toLong())
Napier.i(message = "Loaded ${servers.size} servers with offset $offset", tag = "ServerPagingSource")
Napier.i(message = "limit is ${params.loadSize}", tag = "ServerPagingSource")
LoadResult.Page(
data = servers,
prevKey = if (offset == 0) null else offset - params.loadSize,
nextKey = if (servers.size < params.loadSize) null else offset + params.loadSize
)
} catch (e: Exception) {
LoadResult.Error(e)
}
}
override fun getRefreshKey(state: PagingState): Int? {
Napier.i(message = "getRefreshKey called with state: $state", tag = "ServerPagingSource")
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(state.config.pageSize)
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(state.config.pageSize)
}
}
}
< /code>
class GetPagedServersUseCase(
private val api: BattlemetricsClient,
private val dataSource: ServerDataSource,
private val remoteKeyDataSource: RemoteKeyDataSource
) {
@OptIn(ExperimentalPagingApi::class)
operator fun invoke(query: ServerQuery): Flow {
return Pager(
config = PagingConfig(
pageSize = 10,
enablePlaceholders = false
),
remoteMediator = BattlemetricsRemoteMediator(api, dataSource, remoteKeyDataSource),
pagingSourceFactory = { dataSource.getServersPagingSource(query) }
).flow
}
}
< /code>
Вот вывод журнала от удаленного среднего после запуска приложения и прокрутки вниз: < /p>
2025-06-16 17:06:32.729 31912-31912 RemoteMediator loadType=REFRESH, pageKey=null, API result: 10, nextKey=10,7459421
2025-06-16 17:06:32.857 31912-31912 RemoteMediator RemoteMediator: endOfPaginationReached:false
2025-06-16 17:06:33.687 31912-31912 RemoteMediator loadType=APPEND, pageKey=10,7459421, API result: 10, nextKey=20,26937093
2025-06-16 17:06:33.793 31912-31912 RemoteMediator RemoteMediator: endOfPaginationReached:false
Подробнее здесь: [url]https://stackoverflow.com/questions/79667850/remotemediator-isnt-fetching-data-after-scrolling-in-lazycolumn[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия