Android ViewModel LiveData 文档

Android ViewModel LiveData Documentation

我阅读了文档,但对某些部分感到困惑。

ViewModel objects are designed to outlive specific instantiations of views or LifecycleOwners. This design also means you can write tests to cover a ViewModel more easily as it doesn't know about view and Lifecycle objects. ViewModel objects can contain LifecycleObservers, such as LiveData objects. However ViewModel objects must never observe changes to lifecycle-aware observables, such as LiveData objects. If the ViewModel needs the Application context, for example to find a system service, it can extend the AndroidViewModel class and have a constructor that receives the Application in the constructor, since Application class extends Context.

这部分让我有些困惑

However ViewModel objects must never observe changes to lifecycle-aware observables, such as LiveData objects.

指的是这种实现方式吗?

片段

class AboutFragment : Fragment() {

    private lateinit var aboutViewModel: AboutViewModel
    private var _binding: FragmentAboutBinding? = null

    // This property is only valid between onCreateView and
    // onDestroyView.
    private val binding get() = _binding!!

    override fun onCreateView(
            inflater: LayoutInflater,
            container: ViewGroup?,
            savedInstanceState: Bundle?
    ): View {
        aboutViewModel =
                ViewModelProvider(this).get(AboutViewModel::class.java)

        _binding = FragmentAboutBinding.inflate(inflater, container, false)
        val root: View = binding.root

        val textView = binding.aboutTxt

        //Observe changes
        aboutViewModel.text.observe(viewLifecycleOwner, {
            textView.text = it
        })
        return root
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }
}

视图模型

class AboutViewModel : ViewModel() {

private val _text = MutableLiveData<String>().apply {
    value = "Foobar......"
           
}

fun setText(text: String){ _text.value = text}

val text: LiveData<String> = _text

}

或者这就是他们的意思LiveData<LiveData<Object>>不要做?

这意味着你不应该在视图模型中的实时数据对象上使用 observe,只能在 activity/fragment 中使用,就像你已经在做的那样