Which one is better and please explain why? First...
# codereview
a
Which one is better and please explain 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
    )
}