Last active
October 13, 2022 07:08
-
-
Save burnoo/730902ddb31a5b6db5cda65ff0d46fe5 to your computer and use it in GitHub Desktop.
Jetpack Compose two-way data binding
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private 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 } | |
} | |
// Flow | |
@Composable | |
fun <T> MutableStateFlow<T>.collectAsMutableState( | |
context: CoroutineContext = EmptyCoroutineContext | |
): MutableState<T> = MutableStateAdapter( | |
state = collectAsState(context), | |
mutate = { value = it } | |
) | |
// LiveData | |
@Composable | |
fun <T> MutableLiveData<T>.observeAsMutableState( | |
initialValue: T | |
): MutableState<T> = MutableStateAdapter( | |
state = observeAsState(initialValue), | |
mutate = { postValue(it) } | |
) | |
// RxJava 2/3 | |
@Composable | |
fun <T> PublishSubject<T>.subscribeAsMutableState( | |
initialValue: T | |
): MutableState<T> = MutableStateAdapter( | |
state = subscribeAsState(initialValue), | |
mutate = { onNext(it) } | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It does not compile for me :(
And this is the code.