Android ViewModel Observers 在方向改变之前无法工作(ViewModel 可以工作,但更改为 LiveData 会导致问题)

Android ViewModel Observers not working until orientation change (ViewModel works, but changing to LiveData causes the problem)

我一直在尝试制作一个应用程序,将我的值加倍和加倍到 2 个文本视图中,并且当我使用 viewModel 时,它在所有配置更改中幸存下来。当我将结果类型更改为 MutableLiveData 时,textView 值不会更改,直到我在按下按钮后旋转 phone。这是我的 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)
        }
    }
}

}

这是我的视图模型

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))

}

MutableLiveData 不会自动响应您通过 setValues 设置的更改值。 您需要通过 setValue().

显式更新 MutableLiveData 中的值

为了实现这一点,我建议您将 MutableLiveData 存储在 ViewModel 的字段中以便能够访问它。

例如像这样:

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(): LiveData<List<Float?>> = results
}