Go to a specific item in LazyColumn with index using Paging3 on initial load

I am building a social media app that has a profile page. On it, the user can browse their posts from a vertical grid list. Each post has an id(UUID), authorId(UUID) and an image. When the user clicks on a specific post, a callback function is invoked.

In ProfileScreen:

@Composable
fun PersonalProfileScreen(
    viewModel: PersonalProfileViewModel,
    navController: NavHostController,
    snackbarHostState: SnackbarHostState
) {
    val state = viewModel.state.collectAsStateWithLifecycle()

    val postsLazyPagingItems = state.value
        .userProfileSimplePostsFlow.collectAsLazyPagingItems()

    LazyVerticalGrid(columns = GridCells.Fixed(3)) {
        items(
            count = postsLazyPagingItems.itemCount,
            key = postsLazyPagingItems.itemKey { it.id },
        ) { index ->
            postsLazyPagingItems[index]?.let {
                SimplePostItem(
                    imageBitmap = it.image,
                    onClicked = {
                        navController.navigate(PostsScreenRoute(index, it.authorId))
                    }
                )
            }
        }
    }
}

Clicking on a post triggers a navigation to a PostsScreen which gets the index and authorId of the clicked post as parameters. From there I invoke a method in the PostsViewModel, which starts the loading of posts for the new posts screen.

PostsScreen:

@Composable
fun PostsScreen(
    startItemIndex: Int,
    authorId: String,
    viewModel: PostsViewModel
) {

    val lazyListState = rememberLazyListState()

    val postsLazyPagingItems = viewModel.postsState
        .collectAsStateWithLifecycle().value
        .collectAsLazyPagingItems()

    LaunchedEffect(key1 = true) {
        viewModel.initPosts(startItemIndex, authorId)
    }

    LazyColumn(state = lazyListState) {
            items(
                count = postsLazyPagingItems.itemCount,
                key = postsLazyPagingItems.itemKey { it.id },
                contentType = postsLazyPagingItems.itemContentType { it }
            ) { index ->
                postsLazyPagingItems[index]?.let {
                    PostItem(
                        postModel = it,
                        snackbarHost = snackbarHost,
                        navController = navController
                    )
                } ?: Text(text = "loading")
            }
        }
}

PostsViewModel:

@HiltViewModel
class PostsViewModel @Inject constructor(
    private val postsUseCases: PostsUseCases,
    private val postUseCases: PostUseCases,
    private val database: AppDatabase,
    private val apiService: PostApiService
) : ViewModel() {

    private val _postsState = MutableStateFlow(emptyFlow<PagingData<PostModel>>())
    val postsState: StateFlow<Flow<PagingData<PostModel>>> = _postsState.asStateFlow()

    @OptIn(ExperimentalPagingApi::class)
    fun initPosts(startItemIndex: Int, authorId: String) {
        viewModelScope.launch {
            //clearing cache after each navigation to PostsScreen,
            //before loading any posts
            database.postDao.clearAll()
            postsState.value =
                Pager(
                    initialKey = startItemIndex,
                    config = PagingConfig(
                        pageSize = POSTS_PAGE_SIZE,
                        prefetchDistance = POSTS_PAGE_SIZE,
                        maxSize = 3 * POSTS_PAGE_SIZE,
                        jumpThreshold = 3,
                        enablePlaceholders = true
                    ),
                    remoteMediator = PostRemoteMediator(
                        appDb = database,
                        apiService = apiService,
                        authorId = authorId,
                        startItemIndex = startItemIndex
                    ),
                    pagingSourceFactory = { database.postDao.pagingSource() }
                ).flow.map { pagingData ->
                    pagingData.map { it.asPost().asPostModel(postUseCases) }
                }.cachedIn(viewModelScope)
        }
    }
}

PostRemoteMediator:

@OptIn(ExperimentalPagingApi::class)
class PostRemoteMediator(
    private val appDb: AppDatabase,
    private val apiService: PostApiService,
    private val authorId: String,
    private val startItemIndex: Int
) : RemoteMediator<Int, PostEntity>() {

    override suspend fun load(
        loadType: LoadType,
        state: PagingState<Int, PostEntity>
    ): MediatorResult {
        val loadKey: Int = when (loadType) {
            LoadType.REFRESH -> startItemIndex / POSTS_PAGE_SIZE
            LoadType.PREPEND -> {
                var firstLoadedPage: Int
                withContext(Dispatchers.IO) {
                    firstLoadedPage = appDb.postDao.getFirst().page
                }
                if (firstLoadedPage == 0) {
                    return MediatorResult.Success(endOfPaginationReached = true)
                } else firstLoadedPage - 1
            }

            LoadType.APPEND -> {
                withContext(Dispatchers.IO) {
                    appDb.postDao.getLast().page + 1
                }
            }
        }

        // I use a wrapper class for API responses. This returns list of Posts
        // which can be retrieved via content if the network response code is less than 300,
        // else error is true
        val apiResponse = apiService.getPosts(authorId, loadKey)

        if (!apiResponse.isError) {
            if (apiResponse.content!!.isEmpty()) {
                return MediatorResult.Success(endOfPaginationReached = true)
            }
            val postEntities = apiResponse.content.map {
                val entity = it.asPostEntity()
                entity.page = loadKey
                entity
            }
            appDb.postDao.upsertAll(postEntities)

            return MediatorResult.Success(endOfPaginationReached = false)
        }
        return MediatorResult.Error(ApiResponseException(apiResponse.httpStatusCode))
    }
}

Now, the problem is that I want to set the scroll position to the post item, that the user clicked in the ProfileScreen right after navigating to PostsScreen(during composition). However, I can’t just requestScrollToItem(startItemIndex) as the Posts are being initially loaded and the requested index may still not be available. Also, prepending pushes items at the beginning of the list and the scroll position follows the newly prepended items.

Example scenario:

We have POSTS_PAGE_SIZE = 4 and startItemIndex = 10

During composition, posts list size is 0, so I can’t request scroll to any index. After refresh has completed, the list size is 4 and the item of interest, that we want to keep to the top of the viewport has an index of 2(because the first loaded page during the refresh stage would be startItemIndex / POSTS_PAGE_SIZE, as defined in PostRemoteMediator and page counting begins from 0) so it would be startItemIndex % POSTS_PAGE_SIZE = 2.

However, after the first prepend, the list size is 8(not taking append into consideration), therefore the item of interest has now an index of POSTS_PAGE_SIZE + startItemIndex % POSTS_PAGE_SIZE = 6

After the second append, the item of interest has an index of 2 * POSTS_PAGE_SIZE + startItemIndex % POSTS_PAGE_SIZE = 10

I’ve tried calculating the index offset by observing loadState changes in LaunchedEffect composables in order to call lazyListState.requestScrollToItem(), but any of the variants I’ve tried seemed to be reliable, if working at all. In addition to that, if I request scroll to item with an index small enough to trigger prepending, prepending will continue up until the very first page and the first visible item will change, because the scroll state is kept static, but each prepend “pushes” the items of the new page. Maybe I can wait until all prepends and appends complete and somehow calculate the required scroll offset, but I can’t reliably figure out when the initial prepend and append operations complete. There are no resources regarding this issue and I can’t come up with a working solution. I have never used Paging3 before so maybe I am overcomplicating things needlessly.

Also, I can’t reuse the posts from ProfileScreen as the post image is smaller size(used like a thumbnail).

4

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật