Однако, когда я вызываю функцию обновления() для PagingSource, связанного с LazyPagingItems, весь LazyColumn обновляется, в результате чего пользовательский интерфейс заметно перезагружается и прокручивается обратно вверх. Такое поведение не является идеальным, поскольку оно мешает работе пользователя. Мне просто нужно, чтобы столбец обновлялся новыми данными, если таковые имеются.
Я хочу найти способ обновить данные в LazyPagingItems, не позволяя пользователю замечать какие-либо видимые изменения. Другими словами, я хочу обновлять данные автоматически в фоновом режиме.
Код: Выделить всё
@HiltViewModel
class MainViewModel @Inject constructor(
private val beersRepository: BeersRepository,
) : ViewModel() {
val state: Flow = beersRepository
.getBeers()
.flow
.cachedIn(viewModelScope)
}
//Repository
class BeersRepository @Inject constructor(
private val beersApiService: BeersApiService,
) {
fun getBeers() = Pager(
config = PagingConfig(
pageSize = 10,
enablePlaceholders = true,
),
pagingSourceFactory = { BeersPagingSource(beersApiService = beersApiService) }
)
}
//Paging source
class BeersPagingSource @Inject constructor(
private val beersApiService: BeersApiService,
) : PagingSource() {
override fun getRefreshKey(state: PagingState): Int? {
return state.anchorPosition?.let { anchorPosition ->
state.closestPageToPosition(anchorPosition)?.prevKey?.plus(1)
?: state.closestPageToPosition(anchorPosition)?.nextKey?.minus(1)
}
}
override suspend fun load(params: LoadParams): LoadResult {
val page = params.key ?: 1
return try {
delay(500)
val response = beersApiService.getBeers(page, perPage = 10)
if (response.isSuccessful) {
val beers = response.body()!!.map {
it.toDomain()
}
LoadResult.Page(
data = beers,
prevKey = if (page == 1) null else page - 1,
nextKey = if (beers.isEmpty()) null else page + 1
)
} else {
LoadResult.Error(Exception(response.message()))
}
} catch (e: Exception) {
LoadResult.Error(e)
}
}
}
//And finally the Composable
private fun MainScreenRoute(
viewModel: MainViewModel = viewModel(),
) {
val pagingItems = viewModel.state.collectAsLazyPagingItems()
Scaffold(bottomBar = {
Row(
modifier = Modifier
.background(Color.Transparent)
.fillMaxWidth(),
horizontalArrangement = Arrangement.Center
) {
Button(onClick = {
pagingItems.refresh()
}) {
Text(
text = "Refresh", style = MaterialTheme.typography.bodyLarge
)
}
}
}) {
Surface {
Column(
modifier = Modifier.fillMaxSize()
) {
when (pagingItems.loadState.refresh) {
is LoadState.Error -> {
}
LoadState.Loading -> {
Surface {
Box(
contentAlignment = Alignment.Center,
modifier = Modifier.fillMaxSize()
) {
Text(
text = "Loading...",
style = MaterialTheme.typography.headlineLarge
)
}
}
}
is LoadState.NotLoading -> {
LazyColumn(
verticalArrangement = Arrangement.spacedBy(8.dp),
contentPadding = PaddingValues(8.dp)
) {
items(pagingItems.itemCount) { index ->
val beer = pagingItems[index]!!
BeerCard(
imageUrl = beer.image,
name = beer.name,
description = beer.description,
)
}
}
}
}
}
}
}
}
Подробнее здесь: https://stackoverflow.com/questions/764 ... tpack-comp