Skip to content

Instantly share code, notes, and snippets.

@alexvanyo
Last active January 14, 2022 20:35
Show Gist options
  • Save alexvanyo/d4f9dedefdf223d1a441614c76fe9a91 to your computer and use it in GitHub Desktop.
Save alexvanyo/d4f9dedefdf223d1a441614c76fe9a91 to your computer and use it in GitHub Desktop.
The scroll state hoisting for the HomeRoute
// Copyright 2022 Google LLC.
// SPDX-License-Identifier: Apache-2.0
@Composable
fun HomeRoute(
isExpandedScreen: Boolean,
isArticleOpen: Boolean,
selectedArticleId: String,
onSelectArticle: (String) -> Unit,
onArticleBackPress: () -> Unit,
// ...
) {
// Hoist the lazy list states for the list and the details to
// preserve the scroll through any changes to the content.
val homeListLazyListState = rememberLazyListState()
val articleDetailLazyListStates = allArticles.associate { article ->
key(article.id) {
article.id to rememberLazyListState()
}
}
// ...
if (isExpandedScreen) {
HomeListWithArticleDetailsScreen(
selectedArticleId = selectedArticleId,
onSelectArticle = onSelectArticle,
homeListLazyListState = homeListLazyListState,
articleDetailLazyListStates = articleDetailLazyListStates,
// ...
)
} else {
// if we don't have room for both the list and article details,
// show one of them based on the user's focus
if (isArticleOpen) {
ArticleScreen(
selectedArticleId = selectedArticleId,
articleDetailLazyListState = articleDetailLazyListStates[selectedArticleId],
// ...
)
BackHandler {
onArticleBackPress()
}
} else {
HomeListScreen(
onSelectArticle = onSelectArticle,
homeListLazyListState = homeListLazyListState,
// ...
)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment