https://kotlinlang.org logo
#multiplatform
Title
# multiplatform
m

Mgj

07/07/2020, 1:44 PM
Anyone managed to use android databinding with binding to
StateFlow
or
MutableStateFlow
properties? I've created custom binding adapters before, but i cannot get it to work properly with StateFlows
l

louiscad

07/07/2020, 7:42 PM
What doesn't work exactly?
m

Mgj

07/08/2020, 8:16 AM
I couldnt get two-way binding to work. Usually you would have something like:
Copy code
@InverseBindingAdapter(attribute = "flowText")
@JvmStatic
fun getText(view: MyEditText): String {
    return view.text.toString()
}

@BindingAdapter("flowText")
@JvmStatic
fun setText(view: MyEditText, newValue: String) {
    if (view.text.toString != newValue) {
        view.text = newValue
        view.textChangedListener?.onChange()
    }
}

@BindingAdapter("flowTextAttrChanged")
@JvmStatic
fun setListeners(
    view: MyEditText,
    attrChange: InverseBindingListener
) {
    view.textChangedListener = attrChange
}
But when replacing
String
with
MutableStateFlow<String>
the InverseBindingAdapter would never be called or used by the generated binding code
I ended up just forcing two-way binding on it by subscribing to the StateFlow in the BindingAdapter and updating it with a TextWatcher 🤷 not really ideal but it seems to work
o

Orhan Tozan

07/08/2020, 9:52 AM
Thats why I use LiveData, it has out of the box db support
☝️ 1
m

Mgj

07/08/2020, 11:04 AM
Right, i use LiveData for native android app's but for KMP i'd like to share the viewmodels between platforms... not possible with LiveData
l

louiscad

07/08/2020, 11:22 AM
You have
flow.asLiveData()
m

Mgj

07/08/2020, 11:27 AM
But surely that cannot be used in common code right? I'd have to do that in the android code
o

Orhan Tozan

07/08/2020, 11:27 AM
Yea, just like you use BindingAdapter
m

Mgj

07/08/2020, 11:28 AM
Right. Hmm its an interesting option for sure, thanks
@louiscad
asLiveData
is neat, but i cant seem to find a asMutableLiveData... Seems like i'd still have to make bindingAdapter-like code to enable two-way binding
l

louiscad

07/08/2020, 3:07 PM
@Mgj You can make your own
asMutableLiveData
if you want.
m

Mgj

07/08/2020, 3:08 PM
Should probably have made it more clear, its what i meant by "bindingAdapter-like code". Its still a cool idea but loses some of its appeal
6 Views