Skip to content

Instantly share code, notes, and snippets.

@belinwu
Forked from vishalratna-microsoft/Once.kt
Created June 23, 2022 11:04
Show Gist options
  • Save belinwu/bf99155cdf2257eed92eed7dfcf8e39a to your computer and use it in GitHub Desktop.
Save belinwu/bf99155cdf2257eed92eed7dfcf8e39a to your computer and use it in GitHub Desktop.
Code for Once
import java.util.concurrent.atomic.AtomicInteger
/**
* Construct that helps to restrict the code execution frequency to 1. It will not allow the snippet passed through the close to be executed more than once.
* The first client to execute run() will execute this and other calls to run() will not be respected till reset is called.
*/
class Once {
private val mCounter = AtomicInteger(0)
fun run(code: Closure) {
if (mCounter.compareAndSet(0, 1)) {
code.invoke()
}
}
fun isExecuted(): Boolean {
return mCounter.get() == 1
}
fun reset() = mCounter.set(0)
}
// Represents the closure. Not using default kotlin lambda here to avoid ugly looking <Function0> class generated for Java-Kotlin Compat
interface Closure {
fun invoke()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment