icerockdev / moko-mvvm

Model-View-ViewModel architecture components for mobile (android & ios) Kotlin Multiplatform development
https://moko.icerock.dev/
Apache License 2.0
995 stars 95 forks source link

add two-way binding function to mvvm-flow-compose #180

Closed kramlex closed 1 year ago

kramlex commented 2 years ago
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 }
)

Usage:

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

Based on: https://proandroiddev.com/two-way-data-binding-in-jetpack-compose-1be55c402ec6

Alex009 commented 1 year ago

will be released in 0.15.0