Created
October 13, 2021 11:19
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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