Live Data in android
In Android, "Live Data" is a data holder class that is used to observe changes in data and react to them accordingly.
You can use live data to build reactive user interfaces that automatically update in response to changes in your application's data.
Here are the basic steps to using live data in your Android app:
class MyViewModel : ViewModel() {
? ? private val _items = MutableLiveData<List<String>>()
val items: LiveData<List<String>>
get() = _items
fun loadItems() {
// Load items from a data source
_items.value = listOf("Item 1", "Item 2", "Item 3")
}
}
class MyFragment : Fragment() {
private lateinit var viewModel: MyViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val view = inflater.inflate(R.layout.my_fragment, container, false)
// Set up the view model and observe the items live data
viewModel = ViewModelProviders.of(this).get(MyViewModel::class.java)
viewModel.items.observe(viewLifecycleOwner, Observer { items ->
// Update the UI with the new list of items
})
return view
}?
}?
In this example, the MyViewModel class defines a live data object called _items that holds a list of strings. The loadItems method updates the value of _items whenever new items are loaded from a data source.
The MyFragment class observes the items live data in its onCreateView method. Whenever the value of items changes, the observer's onChanged method is called with the new list of items. The UI can then be updated with the new list of items.
Note that live data objects should only be updated on the main thread. If you need to update a live data object from a background thread, use the postValue method instead of setValue.