I have been trying to make an app that will double and triple my values into 2 textViews, and when I used viewModel, it survived all config changes. When I changed the result type to MutableLiveData the textView values don't change until I rotate the phone, after pressing my button. Here's my MainFragment
class MainFragment : Fragment() {
private var _binding: MainFragmentBinding? = null
private val binding get() = _binding!!
companion object {
fun newInstance() = MainFragment()
}
private lateinit var viewModel: MainViewModel
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = MainFragmentBinding.inflate(inflater, container, false)
return binding.root
}
override fun onActivityCreated(savedInstanceState: Bundle?) {
super.onActivityCreated(savedInstanceState)
viewModel = ViewModelProvider(this)[MainViewModel::class.java]
binding.textView.text = viewModel.getResults().toString()
binding.textView2.text = viewModel.getResults().toString()
val resultsObserver = Observer<List<Float?>>{
binding.textView.text = it[0].toString()
binding.textView2.text = it[1].toString()
}
viewModel.getResults().observe(viewLifecycleOwner, resultsObserver)
binding.action.setOnClickListener {
if(binding.editTextNumberDecimal.text.isNotEmpty()){
viewModel.setValues(binding.editTextNumberDecimal.text.toString())
}else{
binding.textView.text = getString(R.string.no)
binding.textView2.text = getString(R.string.no1)
}
}
}
}
And here is my viewModel
class MainViewModel : ViewModel() {
private var input = ""
private var doubleValue = 0f
private var tripleValue = 0f
fun setValues(value: String){
input = value
doubleValue = input.toFloat() * 2
tripleValue = input.toFloat() * 3
}
fun getResults(): MutableLiveData<List<Float?>> = MutableLiveData(listOf(doubleValue, tripleValue))
}
CodePudding user response:
MutableLiveData
won't react automatically to the changed values you set via setValues
.
You will need to update the values inside of your MutableLiveData
explicitly via setValue()
.
To achive this, I'd suggest you to store your MutableLiveData
in a field of your ViewModel
to be able to access it.
For example like this:
class MainViewModel : ViewModel() {
private var input = ""
private var doubleValue = 0f
private var tripleValue = 0f
private val results = MutableLiveData(listOf(doubleValue, tripleValue))
fun setValues(value: String){
input = value
doubleValue = input.toFloat() * 2
tripleValue = input.toFloat() * 3
// This updates the value inside your LiveData
results.value = listOf(doubleValue, tripleValue)
}
fun getResults(): MutableLiveData<List<Float?>> = results
}