Skip to content

Instantly share code, notes, and snippets.

@rommansabbir
Created October 13, 2021 11:19
Show Gist options
  • Save rommansabbir/939dea3c9e5d1c5ffafb08d4014e794f to your computer and use it in GitHub Desktop.
Save rommansabbir/939dea3c9e5d1c5ffafb08d4014e794f to your computer and use it in GitHub Desktop.
Simple & useful util class to manage execution according to locking state for Android
object ExecutionLocker {
private const val LOGGER = "ExecutionLocker:: isExecutionLocked -> "
// Hold the state of locking
private var isLockingEnabled: Boolean = false
// Get locking status
val isLocked: Boolean
get() = isLockingEnabled
/**
* This method is responsible to enable locking for the given time,
* after the given time is over, release the locking state.
*
* If any error occur, release the locking state.
*
* @param delayMillis, given time to hold the locking state in millis [default is 1 sec]
*/
fun lockExecution(delayMillis : Long = 1000) {
try {
synchronized(this) {
isLockingEnabled = true
log(isLockingEnabled)
Handler(Looper.getMainLooper()).postDelayed(
{
isLockingEnabled = false
log(isLockingEnabled)
},
delayMillis
)
}
} catch (e: Exception) {
e.printStackTrace()
isLockingEnabled = false
}
}
private fun log(status : Boolean){
logThis("$LOGGER $status")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment