Home > other >  What is assigned to the variable updateSection in the offical sample code?
What is assigned to the variable updateSection in the offical sample code?

Time:10-27

The Code A is from offical sample code here.

val (currentSection, updateSection) = rememberSaveable { mutableStateOf(tabContent.first().section) } is a destructuring declaration.

It's a clear that currentSection is assigned by tabContent.first().section

What is assigned to the variable updateSection? Will it be assigned by tabContent.first().content ?

Code A

@Composable
fun InterestsRoute(
   ...
) {
    val tabContent = rememberTabContent(interestsViewModel)
    val (currentSection, updateSection) = rememberSaveable {
        mutableStateOf(tabContent.first().section)
    }
    ...
}


@Composable
fun rememberTabContent(interestsViewModel: InterestsViewModel): List<TabContent> {  
    val uiState by interestsViewModel.uiState.collectAsState()
    val topicsSection = TabContent(Sections.Topics) {
        val selectedTopics by interestsViewModel.selectedTopics.collectAsState()
        TabWithSections(
            sections = uiState.topics,
            selectedTopics = selectedTopics,
            onTopicSelect = { interestsViewModel.toggleTopicSelection(it) }
        )
    }
     ...
    return listOf(topicsSection, peopleSection, publicationSection)
}


enum class Sections(@StringRes val titleResId: Int) {
    Topics(R.string.interests_section_topics),
    People(R.string.interests_section_people),
    Publications(R.string.interests_section_publications)
}

class TabContent(val section: Sections, val content: @Composable () -> Unit)

CodePudding user response:

updateSection is a lambda here used to update the value of the mutable state. Consider this example:

@Composable
fun MyButton() {
    val (count, updateCount) = remember { mutableStateOf(0) }
    Button(
        onClick = { updateCount(count 1) }
    ) {
        Text(text = "$count")
    }
}

Here count is Int and updateCount is (Int) -> Unit. updateCount takes an Int and updates the value of the MutableState (count) to the provided value (here count 1). The above code updates the count text by one everytime the button is clicked.

Coming back to your code, rememberSaveable { mutableStateOf (...) } creates a new MutableState. Its initial value will be tabContent.first().section. currentSection stores the value of this MutableState (initially it will be tabContent.first().section). Now if you want to update the value of this MutableState you can use the updateSection lambda. Just invoke that lambda with the new value and currentSection will be updated automatically.

  • Related