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

Saiedmomen

09/13/2020, 12:20 PM
Here's hoping it hasn't been too many times... Is is intended/ok to have
State
in ViewModels?
👌 3
s

Sean McQuillan [G]

09/14/2020, 6:29 PM
Yes*
State<T>
is intended to be consumed by compose. If your ViewModel is holding UI state for compose-only code, then it works great as a UI-state holder similar to LiveData and is often more concise than alternatives. The idiomatic form of state in a ViewModel looks like this:
Copy code
class MyViewModel: ViewModel() {
    // define a state object & limit writes to only inside this ViewModel
    var clicks by mutableStateOf(0)
        private set

    fun increment() { clicks++ }
}
👍 1