j2emanue
j2emanue

Reputation: 62519

Android architecture component room library - How to handle livedata from DAO

I am not clear how to set the live data that is returned from a dao in room. Lets look at a example DAO in room:

    @Dao
public interface EventDao {

   @Query("SELECT * FROM " + Event.TABLE_NAME + " WHERE " + Event.DATE_FIELD + " > :minDate limit 1")
   LiveData<List<Event>> getEvents(LocalDateTime minDate);

   @Insert(onConflict = REPLACE)
   void addEvent(Event event);

   @Delete
   void deleteEvent(Event event);

   @Update(onConflict = REPLACE)
   void updateEvent(Event event);

}

In particular, i want to look at the getEvents Query call. It will return a list of events in a liveData object. How is this called from the callers end ? Anyone have an example with an observable/flowable as well as plain old java ?

Upvotes: 1

Views: 700

Answers (1)

Moinkhan
Moinkhan

Reputation: 12932

If you are calling from directly activity then your activity must extends LifecycleActivity .

and write below code.

db.getEventDao().getEventList().observe(this, new Observer<List<Event>>() {
    @Override
    public void onChanged(@Nullable List<Event> events) {
        // update your UI.
    }

Live data are lifecycle aware. so live data need to know the lifecycle. So here in observe method first argument need the parameter of LifecycleOwner which is comes from LifecycleActivity.

And if you don't want to use LifeCycleActivity then you must have to use ViewModel. Prefer this link for more detail https://developer.android.com/topic/libraries/architecture/viewmodel.html

Note: In current alpha version LifecycleActivity is not extending AppCompatActivity. In future release it will be part of support library.

Upvotes: 3

Related Questions