Skip to content

Instantly share code, notes, and snippets.

@elifry
Created October 3, 2021 21:49
Show Gist options
  • Save elifry/cc6ab816480c14f35946ca6df3c070e9 to your computer and use it in GitHub Desktop.
Save elifry/cc6ab816480c14f35946ca6df3c070e9 to your computer and use it in GitHub Desktop.
Kotlin infix do after x time
import android.os.Handler
//**/
/ * This is a helper function used for timing, written with infix functions that make it/
/ * possible to write a timer resembling natural language. It contains both seconds and milliseconds/
/ * for convenience./
/ */
/ * Usage:/
/ * Do after 100 seconds {}/
/ * Do after aHundred milliseconds {}/
/ *//
class Do {
enum class duration {
SECONDS, MILLISECONDS
}
infix fun seconds(function: () -> Unit) {
Do.mFormat = duration.SECONDS
Do.handle(function)
}
infix fun milliseconds(function: () -> Unit) {
Do.mFormat = duration.MILLISECONDS
Do.handle(function)
}
companion object {
private var mDuration = 0
var mFormat: duration = duration.MILLISECONDS
fun handle(function: () -> Unit) {
Handler().postDelayed(function,
when (mFormat) {
duration.SECONDS -> mDuration * 1000L
duration.MILLISECONDS -> (mDuration).toLong()
})
}
infix fun after(seconds: Int) : Do {
Do.mDuration = seconds
return Do()
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment