Which one is better and why? First Option: ```cla...
# compose
a
Which one is better and why? First Option:
Copy code
class ViewModel {
    private val _password = MutableStateFlow<String>("")
    val password: StateFlow<String> = _password

    fun onPasswordChanged(password: String) {
        _password.value = password
    }
}

@Composable
fun Screen() {
    val viewModel = remember { ViewModel() } // or viewModel() etc.
    val password by viewModel.password.collectAsState()

    TextField(
        value = password,
        onValueChange = viewModel::onPasswordChanged
    )
}
Second Option:
Copy code
class MutableStateAdapter<T>(
    private val state: State<T>,
    private val mutate: (T) -> Unit
) : MutableState<T> {

    override var value: T
        get() = state.value
        set(value) {
            mutate(value)
        }

    override fun component1(): T = value
    override fun component2(): (T) -> Unit = { value = it }
}


@Composable
fun <T> MutableStateFlow<T>.collectAsMutableState(
    context: CoroutineContext = EmptyCoroutineContext
): MutableState<T> = MutableStateAdapter(
    state = collectAsState(context),
    mutate = { value = it }
)

class ViewModel {
    val password = MutableStateFlow("")
}

@Composable
fun Screen() {
    val viewModel = remember { ViewModel() } // or viewModel() etc.
    val (password, setPassword) = viewModel.password.collectAsMutableState()

    TextField(
        value = password,
        onValueChange = setPassword
    )
}
🧵 1
f
neither. Updates to the
TextField
state must be synchronous and none of your solutions meets that requirement.
a
@Francesc if you have any better solution, please update here
f
consider a state holder that updates the state synchronously. You can, if you need to, use a
snapshotFlow
to observe state updates and push those to the viewmodel