Cyril Find
01/12/2021, 11:42 AMcollectAsLazyPagingItems()
before declaring the NavHost
but it seems to me like I should be able to do it right before LazyColumn
Is there something I’m missing ? (I’ll share the code in the thread 🧵 )Cyril Find
01/12/2021, 11:42 AMconst val LIST = "list"
const val OTHER = "other"
class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContent {
val navController = rememberNavController()
ComposeSampleTheme {
Scaffold(
bodyContent = { MainNavHost(navController) },
bottomBar = { BottomNav(navController) }
)
}
}
}
}
@Composable
fun BottomNav(navController: NavHostController) {
BottomNavigation {
val screens = listOf(LIST, OTHER)
screens.forEach {
BottomNavigationItem(
icon = { Text(it) },
selected = false,
onClick = {
navController.navigate(it) {
launchSingleTop = true
popUpTo = navController.graph.startDestination
}
}
)
}
}
}
@Composable
fun MainNavHost(navController: NavHostController) {
val lazyListState = rememberLazyListState()
val listViewModel: ListViewModel = viewModel()
val items = listViewModel.pagerFlow.collectAsLazyPagingItems()
NavHost(navController = navController, startDestination = LIST) {
composable(LIST) {
LazyColumn(
modifier = Modifier.fillMaxSize(),
state = lazyListState
) {
items(items) { Text("Item #$it") }
}
}
composable(OTHER) { Text("Coucou !") }
}
}
class ListViewModel : ViewModel() {
private val pagingConfig = PagingConfig(pageSize = 10)
private val pager = Pager(pagingConfig) { IntsPagingSource() }
val pagerFlow = pager.flow.cachedIn(viewModelScope)
}
class IntsPagingSource : PagingSource<Int, Int>() {
override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Int> {
val page = params.key ?: 0
val pageSize = params.loadSize
Log.d("FETCH", "PAGE #$page")
return LoadResult.Page(
data = List(pageSize) { (page * pageSize) + it },
prevKey = null,
nextKey = page + 1,
)
}
}
Cyril Find
01/12/2021, 11:44 AMviewModel
and/or items
down inside the composable
, it doesn’t, which is weird to meAndrey Kulikov
01/12/2021, 3:42 PMcollectAsLazyPagingItems
inside the NavHost’s child it doesn’t work?Cyril Find
01/12/2021, 3:56 PMAndrey Kulikov
01/12/2021, 3:57 PMCyril Find
01/12/2021, 3:58 PMCyril Find
01/12/2021, 4:26 PMCyril Find
01/12/2021, 4:27 PMAndrey Kulikov
01/12/2021, 4:27 PMCyril Find
01/12/2021, 4:29 PM