Skip to content

Instantly share code, notes, and snippets.

@burnoo
Last active October 13, 2022 07:08
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save burnoo/730902ddb31a5b6db5cda65ff0d46fe5 to your computer and use it in GitHub Desktop.
Save burnoo/730902ddb31a5b6db5cda65ff0d46fe5 to your computer and use it in GitHub Desktop.
Jetpack Compose two-way data binding
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) }
)
@Abdullqadir
Copy link

Abdullqadir commented Oct 13, 2022

It does not compile for me :(

This is the error message.

"Inheritance from an interface with '@JvmDefault' members is only allowed with -Xjvm-default option"

And this is the code.


import androidx.compose.runtime.Composable
import androidx.compose.runtime.MutableState
import androidx.compose.runtime.State
import androidx.compose.runtime.livedata.observeAsState
import androidx.lifecycle.MutableLiveData

private class MutableStateAdapter<T>( // The error occurs in this line.
    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> MutableLiveData<T>.observeAsMutableState(
    initialValue: T
) : MutableState<T> = MutableStateAdapter(
    state = observeAsState(initialValue), 
    mutate = { postValue(it) }
)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment