Skip to content

Instantly share code, notes, and snippets.

@polson
Last active April 28, 2020 23:27
Show Gist options
  • Save polson/6a7a0d36f10489e2ee8038516df1a948 to your computer and use it in GitHub Desktop.
Save polson/6a7a0d36f10489e2ee8038516df1a948 to your computer and use it in GitHub Desktop.
A job scheduler to process UI jobs without skipping frames
object UIJobScheduler {
private const val MAX_JOB_TIME_MS: Float = 4f
private var elapsed = 0L
private val jobQueue = ArrayDeque<() -> Unit>()
private val isOverMaxTime get() = elapsed > MAX_JOB_TIME_MS * 1_000_000
private val handler = Handler()
fun submitJob(job: () -> Unit) {
jobQueue.add(job)
if (jobQueue.size == 1) {
handler.post { processJobs() }
}
}
private fun processJobs() {
while (!jobQueue.isEmpty() && !isOverMaxTime) {
val start = System.nanoTime()
jobQueue.poll().invoke()
elapsed += System.nanoTime() - start
}
if (jobQueue.isEmpty()) {
elapsed = 0
} else if (isOverMaxTime) {
onNextFrame {
elapsed = 0
processJobs()
}
}
}
private fun onNextFrame(callback: () -> Unit) =
Choreographer.getInstance().postFrameCallback { callback() }
}
@OriginalShakil
Copy link

Do i need to create new kotlin file or i can use with my existing activity or adapter?

@polson
Copy link
Author

polson commented Apr 28, 2020

You can use this anywhere

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