Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

like image 347
NoobieNoob Avatar asked May 17 '26 17:05

NoobieNoob


1 Answers

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.

like image 59
Jeff Lockhart Avatar answered May 19 '26 09:05

Jeff Lockhart



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!