Last active
May 12, 2021 16:06
-
-
Save CyrilFind/5c7d108dd8d030fe7a6a556e43f29f6f to your computer and use it in GitHub Desktop.
Compose Navigation + Paging + ViewModel + Flow
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const 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() // works if done here | |
NavHost(navController = navController, startDestination = LIST) { | |
composable(LIST) { | |
// val items = listViewModel.pagerFlow.collectAsLazyPagingItems() // does not work if done here | |
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, | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment