Home > Back-end >  Update ViewModel and View fails
Update ViewModel and View fails

Time:02-15

I'm trying to use Fragment and ViewModel to update a value from my view using ViewModel.

The problem is that is not updating the value that I want to send via viewModel (now it's hardcoded but I'm thinking in an API request to know a number to set it into my viewModel using postValue and this is not working as I expected)

Here's my code:

Fragment

  private var numberedValue = 0.0  

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupObservers()
        setupView()
    }


    private fun setupObservers(){
        viewModel.obtainNumberedValue()
        viewModel.getNumberedValue().observe(viewLifecycleOwner, { it ->
            numberedValue = it
        })
    }

    private fun setupView(){
        binding.tvValue.text = numberedValue.toString()
    }

ViewModel

private val numberedValue = MutableLiveData<Double>().apply { value = 0.0 }

fun obtainNumberedValue() {
    numberedValue.postValue(200.00)
}


fun getNumberedValued(): LiveData<Double> = numberedValue

Ps. I got 0.0 instead 200.0

CodePudding user response:

I think that you can improve your code if you do something like this

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        setupObservers()
    }


    private fun setupObservers(){
        viewModel.obtainNumberedValue()
        viewModel.getNumberedValue().observe(viewLifecycleOwner, { it ->
            setupTextView(it)
        })
    }

    private fun setupTextView(value: Double) {
        binding.tvValue.text = "$value"
    }

We remove this line private var numberedValue = 0.0 and we add the method inside to the observer method and in in we get any update in the value the ui will be updated

  • Related