Hello - My application has an always-running background service and a user interface (Activity). The background service listens for events that are synced to our CB gateway in the cloud (but for this example, I’ve turned that off). The user can also open an application on the device to view the information that is being captured by the background service. Currently I’ve set up a Manager in both the background service and the foreground Activity.
I’d like to figure out how to write data in the background service and have it accessible from the foreground activity without a roundtrip to the server to minimize unnecessary data usage. Is this possible? Is there a good pattern?
Here’s the identical set up in both the service and the activity:
manager = null;
try {
manager = new Manager(new AndroidContext(this), Manager.DEFAULT_OPTIONS);
} catch (IOException e) {
e.printStackTrace();
}
// Create or open the database
try {
database = manager.getDatabase(Constants.CB_DB_NAME);
} catch (CouchbaseLiteException e) {
e.printStackTrace();
}
In the background service I write to the database:
final Document updateDocument = database.getDocument(Constants.MY_DOC);
try {
updateDocument.update(new Document.DocumentUpdater() {
@Override
public boolean update(UnsavedRevision newRevision) {
Map<String, Object> props = newRevision.getProperties();
// <Set properties>
newRevision.setProperties(props);
return true;
}
});
} catch (CouchbaseLiteException e) {
Log.e("Scan", "CouchbaseLiteException thrown", e);
}
In the foreground I listen for changes and load the latest version when the activity is resumed.
View myView = database.getView(Constants.MY_VIEW);
if(myView.getMap() == null) {
myView.setMap(new Mapper() {
@Override
public void map(Map<String, Object> document, Emitter emitter) {
if(document.containsKey(TYPE) &&
Objects.equals(document.get("type"), Constants.MY_DOC_ID)) {
emitter.emit(MY_STUFF, document.get(MY_STUFF));
}
}
}, "1.0");
}
LiveQuery myQuery = myView.createQuery().toLiveQuery();
myQuery.addChangeListener(new LiveQuery.ChangeListener() {
@Override
public void changed(LiveQuery.ChangeEvent event) {
String stuff = (String)event.getRows().getRow(0).getDocument().getProperty(MY_STUFF);
TextView textView = (TextView) findViewById(R.id.myStuff);
textView.setText(myStuff);
}
});
The activity doesn’t receive any update events when I write in the background.
Any good patterns here or do I need to make that roundtrip to the server?
Thanks