Skip to content

Instantly share code, notes, and snippets.

@sgammon
Created September 1, 2019 00:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgammon/620437080dfe98e3c09666f2e16835ce to your computer and use it in GitHub Desktop.
Save sgammon/620437080dfe98e3c09666f2e16835ce to your computer and use it in GitHub Desktop.
Firebase transaction sample in Kotlin
val dbReference: DatabaseReference = firebase.ref("some/db/path")
dbReference.runTransaction(object: Transaction.Handler {
/**
* This method will be called once, at completion, with the results of the transaction.
*
* @param error null if no errors occurred, otherwise it contains a description of the error
* @param committed True if the transaction successfully completed, false if it was aborted or
* an error occurred
* @param currentData The current data at the location
*/
override fun onComplete(error: DatabaseError?, committed: Boolean, currentData: DataSnapshot?) {
// completion function
}
/**
* This method will be called, possibly multiple times, with the current data at this location. It is
* responsible for inspecting that data and returning a [Result] specifying either the desired new data at the
* location or that the transaction should be aborted.
*
* Since this method may be called repeatedly for the same transaction, be extremely careful of any side effects
* that may be triggered by this method. In addition, this method is called from within the Firebase Database
* library's run loop, so care is also required when accessing data that may be in use by other threads in your
* application.
*
* Best practices for this method are to rely only on the data that is passed in.
*
* @param target The current data at the location. Update this to the desired data at the location.
* @return Either the new data, or an indication to abort the transaction
*/
override fun doTransaction(target: MutableData): Transaction.Result {
// ... transaction logic ...
}
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment