When using StateFlow and DataBinding together, the BindingAdapter's method is called twice

150 views Asked by At

MainActivity

class MainActivity : AppCompatActivity() {
    private val viewModel: MainViewModel by lazy { ViewModelProvider(this).get(MainViewModel::class.java)}
    private lateinit var binding: ActivityMainBinding

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_main)

        binding.lifecycleOwner = this
        binding.viewModel = viewModel
    }
}

ViewModel

class MainViewModel : ViewModel() {
    private val _text = MutableStateFlow("Initial Text")
    val text = _text.asStateFlow()

}

activity_main.xml

<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">

    <data>
        <variable
            name="viewModel"
            type="com.wantique.bindingadaptertest.MainViewModel" />

    </data>

    <androidx.constraintlayout.widget.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        tools:context=".MainActivity">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:convertText="@{viewModel.text}"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent" />

    </androidx.constraintlayout.widget.ConstraintLayout>
</layout>

Binding Adapter

object BindingAdapters {
    @BindingAdapter("convertText")
    @JvmStatic
    fun convertText(view: TextView, text: String) {
        Log.d("DataBindingTest", text)
        view.text = text
    }
}

Output Log

2023-08-16 01:16:46.492 31921-31921 DataBindingTest         com.wantique.bindingadaptertest      D  Initial Text
2023-08-16 01:16:46.510 31921-31921 DataBindingTest         com.wantique.bindingadaptertest      D  Initial Text

When I use StateFlow and DataBinding together, the BindingAdapter's method is called twice. It seems as if the initial value of StateFlow is being collected twice. However, when assigning a new value to StateFlow, the BindingAdapter's method is called only once. What am I missing or misunderstanding?

I've tried debugging but couldn't find the exact cause.

0

There are 0 answers