Insert to room in service not updating LiveData in

2019-08-15 02:01发布

问题:

I'm using room to communicate data fetched by a foreground Location service with the an activity. The service connects to the viewmodel and does insert data, the activity however does not receive updated LiveData from the viewmodel, it is however able to fetch a LiveData> object at the begining, with accurate size when restarting the app. What am I missing here? I need to insert new data into the db, so if I do need to use MutableLiveData in the service and postValue, then I would have to post the entire list everytime...

Activity.java


@Override
protected void onCreate( Bundle savedInstanceState ) {
    super.onCreate( savedInstanceState );

    setContentView( R.layout.track_activity );

    mViewModel = ViewModelProviders.of( this ).get( ViewModel.class );

    mViewModel.getAllData().observe( this, ( @Nullable final <List<eData>> data ) -> {

        if ( data!= null )
            Log.d("DATACOUNT", String.valueOf(data.size()) );

    } );
}

Service.java

@Override
public void onCreate() {
    super.onCreate();

    AppDatabase mDB = AppDatabase.getDatabase( this.getApplication() );
    mDataDao = mDB.dataDao();

    mExecutor = Executors.newSingleThreadExecutor();

}

...

private void receiveLocation( LocationResult locationResult ) {

    ...
    mExecutor.execute( () -> mDataDao.insertData( new eData( ... ) ) );

}

DataDao.java

@Dao
public interface DataDao {

    @Query( "SELECT * FROM eData" )
    LiveData<List<eData>> getAllData();

    @Insert
    long insertData( eData data );
}

AppDatabase.java

@Database(entities = { eData.class }, version = 1 )
public abstract class AppDatabase extends RoomDatabase {

    public abstract DataDao dataDao();

    private static AppDatabase INSTANCE;

    public static AppDatabase getDatabase( final Context context ) {
        if ( INSTANCE == null ) {
            synchronized ( AppDatabase.class ) {
                if ( INSTANCE == null ) {
                    INSTANCE = Room.databaseBuilder( context.getApplicationContext(),
                            AppDatabase.class, "locationapp" )
                                       .build();
                }
            }
        }
        return INSTANCE;
    }

The Repository and Database are Singletons. But somewhow the LiveData observed in my activity does not update when inserting entities in the service, which it does insert into the database, as when I restart the app, the count goes up.