Sobes.tech
Junior — Middle

How can you set up a watcher for changes in LiveData?

sobes.tech AI

Answer from AI

In Android, to set up a observer for changes in LiveData, the observe method is used, which takes a LifecycleOwner and an Observer.

Example:

liveDataObject.observe(this /* LifecycleOwner */, Observer { data ->
    // Handling updated data
    textView.text = data
})

Here, this is usually an Activity or Fragment that implements LifecycleOwner. The Observer is a function or object that reacts to data changes in LiveData. This approach allows automatic management of the observer's lifecycle, preventing memory leaks.