zt
01/09/2023, 6:14 PMval videos = viewModel.videos.collectAsLazyPagingItems()
LazyColumn(
modifier = Modifier
.fillMaxSize()
.padding(horizontal = 14.dp),
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
items(
items = videos,
key = { it.id }
) { video ->
if (video == null) return@items
VideoCard(video)
}
}
zt
01/09/2023, 6:20 PMZun
01/09/2023, 8:24 PMzt
01/09/2023, 8:29 PMclass HomeViewModel(
private val innerTube: InnerTubeRepository
) : ViewModel() {
val videos = Pager(PagingConfig(4)) {
object : PagingSource<String, DomainVideoPartial>() {
override suspend fun load(params: LoadParams<String>) = try {
val response = innerTube.getRecommendations(params.key)
LoadResult.Page(
data = response.items,
prevKey = null,
nextKey = response.continuation
)
} catch (e: Exception) {
e.printStackTrace()
LoadResult.Error(e)
}
override fun getRefreshKey(state: PagingState<String, DomainVideoPartial>): String? = null
}
}.flow.cachedIn(viewModelScope)
}
Zun
01/09/2023, 8:41 PMzt
01/10/2023, 1:03 AM@Composable
fun <T : Any> LazyPagingItems<T>.rememberLazyListState(): LazyListState {
// After recreation, LazyPagingItems first return 0 items, then the cached items.
// This behavior/issue is resetting the LazyListState scroll position.
// Below is a workaround. More info: <https://issuetracker.google.com/issues/177245496>.
return when (itemCount) {
// Return a different LazyListState instance.
0 -> remember(this) { LazyListState(0, 0) }
// Return rememberLazyListState (normal case).
else -> androidx.compose.foundation.lazy.rememberLazyListState()
}
}
It really sucks that this has been an issue since very early 2021. I hope they fix it soon cause its pretty critical in my opinionZun
01/10/2023, 9:08 AM