I'm using the androidx-paging compose library with...
# compose
z
I'm using the androidx-paging compose library with a LazyColumn, but it keeps losing its scroll position when navigating away. I have the following code
Copy code
val 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)
    }
}
Shouldn't the key fix this issue? It's a unique value
z
How does your videos variable look like in your ViewModel ?
z
Copy code
class 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)
}
z
z
Thank you This workaround worked for me:
Copy code
@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 opinion
z
I’m using the same workaround. Only issue is that programmatically scrolling to a position no longer works
122 Views