Andrey.Kozyrev
Andrey.Kozyrev

Reputation: 669

Android compose: LazyColumn and Room with suspend DAO

I want to do a seemingly simple thing in Android Compose, display a large list dynamically loaded from a Room database:

LazyColumn(count) { index ->
    val myItemModel = db.itemDAO().getAt(index)
    MyItemView(myItemModel)
}

DAO methods should be suspend to play nice. But suspend functions obviously cannot be called from @Composable functions. I do not want to do runBlocking. I can turn myItemModel into proxy and inflate it in LaunchedEffect but then LazyColumn's scrolling is broken as it cannot predict the viewport offset position, because the items have different content and height.

What is the canonical way to display large list in LazyColumn?

Upvotes: 0

Views: 867

Answers (1)

Jan Bína
Jan Bína

Reputation: 7218

Firstly, it's not a good idea to load your items from database one by one. Load some larger chunks of your data, something like 100 items at a time maybe.

The canonical way of loading data from db and displaying them in LazyColumn would be using a ViewModel. You would do the loading on the background thread in your ViewModel, publish it as a StateFlow<List<MyItem>>, collect it flow in your composable and display it in LazyColumn.

For the loading, you can also use the paging library. It is nicely integrated with Compose - there is a collectAsLazyPagingItems() function for collecting the items and items() function, which will feed them directly into your LazyColumn.

Upvotes: 2

Related Questions