How to Save & Restore the Scroll Position of a LazyColumn using Paging 3 RemoteMediator? Compose

25 Views Asked by At

I am looking an approach to store current Scroll Position using Paging_3 when users end the application and restore the same when users re-launch the app.

I tried implementing lazyListState.firstVisibleItemIndex but it only work best for offline if no data changes.

But when using RemoteMediator the data loads first at stated scroll position but suddenly after finishing API call scroll animated to a random position.

Here my implementation:

@Composable
fun ArticleScreen(viewModel: ArticleViewModel = hiltViewModel()) {

    //fetch scroll position from shared prefs
    val scrollIndex = remember { viewModel.getScrollIndex }
    val lazyArticleItems = viewModel.articlesFlows.collectAsLazyPagingItems()

    //set sharedpref scroll position
    val lazyListState = rememberLazyListState(
        initialFirstVisibleItemIndex = scrollIndex
    )

    // collect and store scroll position into sharedprefs
    LaunchedEffect(key1 = lazyListState, block = {
        snapshotFlow {
            lazyListState.firstVisibleItemIndex
        }.debounce(1000L)
            .collectLatest { index ->
               viewModel.setScrollIndex(index)
                Log.d("GoogleIO","Snapshot position: $index")
            }
    })

    Box(modifier = Modifier.fillMaxSize()) {
        if(lazyArticleItems.itemCount < 1 && lazyArticleItems.loadState.refresh is LoadState.Loading) {
            CircularProgressIndicator(Modifier.align(Alignment.Center))
        } else {
            ArticleList(lazyListState, lazyArticleItems)
        }
    }
}
0

There are 0 best solutions below