https://kotlinlang.org logo
#flow
Title
# flow
j

joadar

11/22/2021, 5:56 PM
Hello guys 🙂 I try to update the data into a Flow, but I have this (working) solution:
Copy code
private val _uiState = MutableStateFlow(DeveloperUiState(isLoading = true, sectionsItems = DeveloperSections()))
val uiState: StateFlow<DeveloperUiState> = _uiState.asStateFlow()

...

_uiState.update {
    it.copy(
        sectionsItems = it.sectionsItems.copy(
            userSection = it.sectionsItems.userSection?.copy(
                options = it.sectionsItems.userSection.options.copy(
                    userPremium = it.sectionsItems.userSection.options.userPremium.copy(
                        isSelected = isChecked,
                        summary = if (isChecked) "Yes" else "No"
                    )
                )
            )
        )
    )
}
Is there a way to reduce this path to edit a specific variable from an object? Thanks for your inputs!
n

Nick Allen

11/22/2021, 6:02 PM
I'd create extension methods for sectionItems, userSection, options, and userPremium, that call each other. Not less code, but much easier to read.
👍 1
j

joadar

11/22/2021, 6:12 PM
Yes good idea. So this way to update is correct?
n

Nick Allen

11/22/2021, 6:12 PM
Kotlin team has been playing with the idea of allowing mutation operators on var's of immutable types where the var is reassigned to the modified copy. So I think you'll be able to do something like this sometime in the future if all goes well:
Copy code
_uiState.update {
    var state = it
    state.sectionsItems.userSection.options.userPremium.isSelected = isChecked
    state.sectionsItems.userSection.options.userPremium.summary = if (isChecked) "Yes" else "No"
    state
}
No guarantees though and I'm no expert on the proposal so I may be off a bit.
As fare as I know, that's the only way to do it ... which is why they are looking at ways to make it better.
j

joadar

11/22/2021, 6:16 PM
Okay perfect, thank you Nick for your help!
3 Views