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