In my ViewModels I have properties that are MutableState and I only want to change their .value inside the ViewModel but not in the screens.
This is easily fixed by having two properties like this
private val _someScreenState = mutableStateOf("something")
val someScreenState: State<String> = _someScreenState
But when having a lot of properties this becomes annoying look at and confusing to work with. So is there a way to do the same thing but without having to instatiate two State properties?
I know kotlin has a nice way of writing getters and setters for properies inside classes for example like this
var someScreenState = mutableStateOf("something")
private set()
This would do the trick since the property itself is a var (mutable) while having a private setter. But with compose's State I'm not trying to change the property itself but rather it's someScreenState.value property so you would still be able to change someScreenState.value outside of the ViewModel.
I've used state objects like a ScreenState class which holds all the State properties inside, but a lot of properties have to be of type StateFlow and with state objects you can't pick and choose which is State and which is StateFlow (there are other problems with state objects as well that's why I've been trying to move away from them).
This is possible using the new experimental Kotlin backing property changes. This feature requires Kotlin 1.7, a new K2 compiler, and some changes to enable it.
It would be something like this.
(This may not be the exact syntax as it is experimental as there have been a lot of discussions around this for a long time)

Related article
https://nikoladespotoski.medium.com/overriding-backing-property-type-in-kotlin-1-7-5581cd30e77a
Related GitHub issue for full discussion reference,
https://github.com/Kotlin/KEEP/issues/278
YouTrack issue link
https://youtrack.jetbrains.com/issue/KT-14663
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With