Database.addChangeListener not work some time in Coubaselite 1.4.4 .
Below is my code
database?.addChangeListener { event ->
//using for only changed documents
Log.e("changes",""+event.changes)
val query = database?.createAllDocumentsQuery()
query?.allDocsMode = Query.AllDocsMode.ALL_DOCS
var result: QueryEnumerator? = null
result = query?.run()
val it = result
if (it != null) {
arrayList.clear()
while (it.hasNext()) {
val row = it.next()
if (row.documentId.startsWith("refill-device-SERIAL-")) {
obj = JSONObject(row.document.properties)
val canisters = gson.fromJson(obj.toString(), Canisters::class.java)
arrayList.add(canisters)
}
}
}
canistersArrayList.postValue(arrayList)
}
Above code not fire sometime… What I should do if I want to get every change events from database?
I don’t know why your code wouldn’t be catching all database changes.
But you should be using a document change listener instead, since you only care about specific documents. Then you can quickly ignore changes where the docID doesn’t start with the prefix. Never mind; I was misremembering the old API. The event you get from the database change listener will tell you which documents changed and you can scan that.
Also, you’re using the all-docs query very inefficiently. If you only want a range of docIDs (the ones that start with the prefix), then set the startKey and endKey so you only iterate that range, instead of looping over every document in the db.
Set the query’s startKey to "refill-device-SERIAL-" and endKey to "refill-device-SERIAL-\uFFFE".
(The Unicode character at the end of the endKey is just there because it’s greater than anything else that’s likely to be in a key. You could use "refill-device-SERIAL-zzzzz if you knew none of the serials started with zzzzz or higher; using a high-valued character is more reliable.)