Reputation: 3449
I read the documentation but became confuse on some part.
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.
This part is somewhat confusing for me
However ViewModel objects must never observe changes to lifecycle-aware observables, such as LiveData objects.
Is this referring to this kind of implementation?
Fragment
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
}
}
ViewModel
class AboutViewModel : ViewModel() {
private val _text = MutableLiveData<String>().apply {
value = "Foobar......"
}
fun setText(text: String){ _text.value = text}
val text: LiveData<String> = _text
}
Or this is what they mean LiveData<LiveData<Object>>
not to do?
Upvotes: 0
Views: 120
Reputation: 73753
it means you should never use observe
on a livedata object in your viewmodel, only in activity/fragment like you are already doing
Upvotes: 1