https://kotlinlang.org logo
#compose
Title
# compose
s

Stephen Vinouze

02/02/2022, 3:55 PM
Hello , I wanted to get your opinion on this small piece of code. I have a
LandingViewModel
exposing a
LandingViewState
Copy code
data class LandingViewState(
    val firstPlayerName: String = "",
    val secondPlayerName: String = "",
    val canPlay: Boolean = false,
)
I would like the last attribute to be derived from name arguments while only exposing the
viewState
– you can see that as a reducer. I haven't been able to find a better pattern than this
Copy code
@HiltViewModel
class LandingViewModel @Inject constructor() : ViewModel() {

    val viewState: LandingViewState by derivedStateOf {
        LandingViewState(
            firstPlayerName, secondPlayerName, firstPlayerName.isNotEmpty() && secondPlayerName.isNotEmpty()
        )
    }
    var firstPlayerName: String by mutableStateOf("")
    var secondPlayerName: String by mutableStateOf("")

}
So I've made the
viewState
as a derived state and exposed the other attributes. Ideally, I'd only expose the
viewState
as a state and transform the
canPlay
on the fly as I'd have done with a reducer. But I can't figure out how to do it with compose
mutableStateOf
m

myanmarking

02/02/2022, 8:47 PM
Try not to expose any compose dependencies in the viewModel, apart from some(for instance, SnapShotList). Your model should be like
data class LandingViewState(
val firstPlayerName: String = "",
val secondPlayerName: String = ""
){
val canPlay: Boolean = xxx
}
and expose it via flow. If you do not want to use flow, just use a mutableState of the viewState. There is no need to use separate states i think
and to update the state, you do: viewState.value = viewState.copy(firstPlayerName = xxx). That way, you do not need any derivedState in the viewModel. It’s actually better with flow: viewState.update{it.copy(xxx)). But that works too
s

Stephen Vinouze

02/03/2022, 7:49 AM
Thanks for the insight! I didn't realize I was exposing compose dependencies in the VM via the derivedStateOf 🤦
4 Views