Search code examples
androidandroid-roomviewmodelandroid-architecture-componentsbackground-service

LiveData does not observe changes when updated with SyncAdapter / different Thread


I have a SyncAdapter which inserts messages:

public class SyncAdapter extends AbstractThreadedSyncAdapter {
    @Override
    public void onPerformSync(Account account, Bundle extras, String authority, ContentProviderClient provider, SyncResult syncResult) {
       messageDAO.insert(..);
    }
}

And I have an Activity which displays a filtered part of these messages:

    protected Observer<List<MessageEntity>> messageOberserver;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        this.messageOberserver = new Observer<List<MessageEntity>>() {
          @Override
          public void onChanged(List<MessageEntity> messages) {
            Log.v("tmp", "messages have changed");
            messageAdapter.setData(messages);
        }
      }

        MessageViewModel messageViewModel = ViewModelProviders.of(this).get(MessageViewModel.class);
        messageDAO.findMessagesForTopic(this.topicId).observe(this, this.messageOberserver);
  }
DAO:
    @Query("SELECT * FROM Message WHERE messageTopicId = :topicId")
    LiveData<List<MessageEntity>> messageDAO.findMessagesForTopic(String topicId);

Now the problem is that the observer does not recognize changes to the message table. Changes are displayed if I re-open the activity. What is a proper way for the SyncAdapter to tell the Activity that it should check for changes? I read about postValue(), but I don't know how to use it. The SyncAdapter does not know the partial Message data which is displayed by the Activity.

--

Btw. the code works if I update from other places (not SyncAdapter).


Solution

  • This may be a result of running your sync adapter in another process, which the sync adapter service documentation directs by default. Try removing the android:process=":sync or similar line from the service in AndroidManifest.xml. This will run the sync adapter in the same process as your application activity.