Skip to content

Instantly share code, notes, and snippets.

@drulabs
Last active August 8, 2018 05:32
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 drulabs/426317a468b12a9a31a7bcdbf0a53670 to your computer and use it in GitHub Desktop.
Save drulabs/426317a468b12a9a31a7bcdbf0a53670 to your computer and use it in GitHub Desktop.
import android.database.sqlite.SQLiteDatabase
// Add an extension function to perform SQLite operations
// This is a higher order function as it takes a function as parameter (operation)
// @param operation: a function that takes no parameter and returns nothing
fun SQLiteDatabase.performDBTransaction(operation: () -> Unit) {
beginTransaction()
operation() // this is the passed function
endTransaction()
}
val db: SQLiteDatabase = DBHandler.getInstance(...)
// invoke the extension function like a pro
db.performDBTransaction {
// Any DB transaction here
// without worrying whether you called endTransaction()
}
// invoke the function like DSL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment