Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LiveData is abstract android

I tried initializing my LiveData object and it gives the error: "LiveData is abstract, It cannot be instantiated"

LiveData listLiveData = new LiveData<>();

like image 247
Idee Avatar asked Aug 10 '17 22:08

Idee


People also ask

What is LiveData Android?

LiveData is an observable data holder class. Unlike a regular observable, LiveData is lifecycle-aware, meaning it respects the lifecycle of other app components, such as activities, fragments, or services. This awareness ensures LiveData only updates app component observers that are in an active lifecycle state.

What is difference between ViewModel and LiveData?

ViewModel : Provides data to the UI and acts as a communication center between the Repository and the UI. Hides the backend from the UI. ViewModel instances survive device configuration changes. LiveData : A data holder class that follows the observer pattern, which means that it can be observed.

Is LiveData deprecated Android?

This function is deprecated. This extension method is not required when using Kotlin 1.4.

Can we use LiveData without ViewModel?

No, It is not mandatory to use LiveData always inside ViewModel, it is just an observable pattern to inform the caller about updates in data.


1 Answers

In a ViewModel, you may want to use MutableLiveData instead.

E.g.:

class MyViewModel extends ViewModel {
  private MutableLiveData<String> data = new MutableLiveData<>();

  public LiveData<String> getData() {
    return data;
  }

  public void loadData() {
    // Do some stuff to load the data... then
    data.setValue("new data"); // Or use data.postValue()
  }
}

Or, in Kotlin:

class MyViewModel : ViewModel() {
  private val _data = MutableLiveData<String>()
  val data: LiveData<String> = _data

  fun loadData() {
    viewModelScope.launch {
      val result = // ... execute some background tasks
      _data.value = result
    }
  }
}
like image 186
E.M. Avatar answered Oct 21 '22 11:10

E.M.