I converted one of my apps to the new Firestore. I am doing things like saving a document on a button click, and then in the onSuccess
listener, going to a diff
I found out how to do it using info at http://blog.farifam.com.
Basically you must use SnapshotListeners
instead of OnSuccess
listeners for offline work.
Also, you cannot use Google's tasks because they won't compete offline.
Instead (since Tasks are basically Promises), I used the Kotlin Kovenant library which can attach listeners to promises. One wrinke is that you must configure Kovenant to allow multiple resolution for a promise, since the event listener can be called twice (once when the data is added to the local cache, and once when it is synced to the server).
Here is an example snippet of code, with success/failure listeners, that runs both online and offline.
val deferred = deferred() // create a deferred, which holds a promise
// add listeners
deferred.promise.success { Log.v(TAG, "Success! docid=" + it.id) }
deferred.promise.fail { Log.v(TAG, "Sorry, no workie.") }
val executor: Executor = Executors.newSingleThreadExecutor()
val docRef = FF.getInstance().collection("mydata").document("12345")
val data = mapOf("mykey" to "some string")
docRef.addSnapshotListener(executor, EventListener { snap: DocumentSnapshot?, e: FirebaseFirestoreException? ->
val result = if (e == null) Result.of(snap) else Result.error(e)
result.failure {
deferred.reject(it) // reject promise, will fire listener
}
result.success { snapshot ->
snapshot.reference.set(data)
deferred.resolve(snapshot) // resolve promise, will fire listener
}
})