Skip to content

Instantly share code, notes, and snippets.

@sergchil
Created July 25, 2018 10:59
Show Gist options
  • Save sergchil/4ba3aaa0d68c213cd0fff42721f4bcc4 to your computer and use it in GitHub Desktop.
Save sergchil/4ba3aaa0d68c213cd0fff42721f4bcc4 to your computer and use it in GitHub Desktop.
Helper class that invokes once
import java.util.concurrent.atomic.AtomicBoolean
/**
* Created with ❤ by Sergey Chilingaryan
*/
// Yes, I made class for this simple call
// but this is more readable than having booleans and checking ifs
// I hate using booleans with ifs to do things once
class Once {
private val done = AtomicBoolean()
fun run(task: () -> Unit?) {
if (done.get()) return
if (done.compareAndSet(false, true)) {
task()
}
}
}
@sergchil
Copy link
Author

USAGE

private val once = Once()
once.run { //YOUR_CODE_HERE }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment