Make Room DAO return LiveData<Cursor>

Viewed 3040

Do you know how to make Room DAO return a LiveData<Cursor> ?


I need to request a lot of objects from my DB.
Because of memory issues, I don't afford an heavy object list, I need a Cursor.
Of course data could be updated and I need to be notify when it occurred.
So a LiveData<Cursor> should be a good solution.

But, when I compile this :

@Dao
public interface FooDao {

    @Query("SELECT * FROM foo")
    LiveData<Cursor> getFoo();

}

Android Studio says to me : Error:(22, 22) error: Not sure how to convert a Cursor to this method's return type

Well... Please do not tell me we can't get notify of data updates with a Cursor :/

2 Answers

you can use instance of RoomDatabase if using Room 2.x

RoomDatabase appDatabase;
...

public LiveData<Cursor> getCursorLiveData(){
    return appDatabase.getInvalidationTracker().createLiveData(new String[]{"table1","table2"}, true, ()->{
       Cursor cursor = ...;
       return cursor;
    }
}

table1, table2 are tables to observe. provide true as second param if you want the computeFunction(last function arg) will be done in a transaction

Related