1

I'm trying to update TextInputEditText text via data-binding after I get some data from BE API call. My solution works perfectly if code is not executed inside coroutine. If variable is set inside coroutine EditText does not get updated. My XML code:

<com.google.android.material.textfield.TextInputEditText
                android:layout_width="match_parent"
                android:layout_height="40dp"
                android:text="@={ viewModel.name }" />

My viewModel code:

var name: String = ""
        get() = field.trim()
        set(value) {
            field = value
            //some other unrelated code
        }
...
fun getName(){
    name = "first"
    viewModelScope.launch(Dispatchers.Main) {
        name = "second"
    }
}

TextInputEditText will be updated to "first" but not to "second". I've tried with other dispatchers. I've also verified via debugger that "name" variable setter is being triggered both times. It's just not updating the EditText. Any ideas on what could cause this?

Ole Pannier
  • 3,208
  • 9
  • 22
  • 33

2 Answers2

1

In my case, the problem was solved by setting the value of the lifecycleOwner property in the following code. The data binding is now done as intended.

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
  super.onViewCreated(view, savedInstanceState)
    
  postDetailViewModel = ViewModelProvider(this)[PostDetailViewModel::class.java]
  binding.varPostDetailViewModel = postDetailViewModel
  binding.lifecycleOwner = this // Add this line
    
  coroutineScope.launch {
    arguments?.let {
      val args = PostDetailFragmentArgs.fromBundle(it)
      postDetailViewModel.getPostDetail(args.postID)
    }
  }
}
Fish
  • 45
  • 6
0

Your name field needs to be observable.

Right now, nothing is telling the EditText that the field was updated and needs to be rebound. You're probably seeing "first" from initially setting the viewModel on the binding.

Review the documentation on obervability.

My answer to another similar question might also be helpful.

dominicoder
  • 9,338
  • 1
  • 26
  • 32