Last active
April 28, 2020 23:27
-
-
Save polson/6a7a0d36f10489e2ee8038516df1a948 to your computer and use it in GitHub Desktop.
A job scheduler to process UI jobs without skipping frames
This file contains 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 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() } | |
} |
You can use this anywhere
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Do i need to create new kotlin file or i can use with my existing activity or adapter?