What's the best way to use TabRow Tabs with viewModel in Compose?

250 Views Asked by At

Currently I'm developing a "pager" , my idea is to fill from the database the "tabs", and each tab will have an id, this Id will help me to query a list from room with a list of items, so basically tab rows and the content will be the "same" list but it will fetched with different items. like this:

TeamA | TeamB| TeamC| TeamD

ListA | ListB. | ListC | ListD. (the list will use the Id from the tab and query the database with this id and fill the list.

I have something like this:

 @Composable
    fun TeamTabs(tabList: List<TeamTabRow>) {
        var tabIndex by remember { mutableIntStateOf(tabList.lastIndex) }
    
    
        Column(Modifier.fillMaxWidth()) {
            TabRow(
                selectedTabIndex = tabIndex,
            ) {
                tabList.forEachIndexed { index, tabRow ->
                    Tab(
                        selected = tabIndex == index,
                        onClick = {},
                        selectedContentColor = AppTheme.colors.tabActive01
                    ) {
                        Text(
                            text = tabRow.tabTitle,
                        )
    
                    }
                }
            }
            when (tabList.getOrNull(tabIndex)) {
                is TeamTabRow.Players -> {
                   // ScreenWithList is just a lazyColumn, but how I can retrieve the data from here?
                    ScreenWithList()
                }
    
                is TeamTabRow.Stats -> {
    // ScreenWithStats is just a lazyColumn, 
                    ScreenWithStats()
                }
    
                null -> TODO()
            }
        }
    }
    
    sealed class TeamTabRow(val tabTitle: String, val id: Int) {
        data class Players(val title: String) : TeamTabRow(title, 1)
        data class Stats(val title: String) : TeamTabRow(title, 2)
    }

In the composable editor I can't "see" or visualize the preview using this code so I have the following code:

  when (val item =tabList.getOrNull(tabIndex)) {
            is TeamTabRow.Players -> {
                if(LocalView.current.isInEditMode){
                    ScreenWithMockedDataList()
                }else{
                    ScreenWithListAndViewModel(item.id)
                }

            }

using LocalView.current.isInEditMode to preview the changes, but what would be the best to fetch the data for each screen using tabs/pager style, in a Fragment pager I would use a Fragment and each fragment will have his own viewModel and fetch the data, but how I can achieve the same with compose?

0

There are 0 best solutions below