Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package ein.core.coroutine
- import kotlinx.coroutines.*
- import kotlin.browser.window
- import kotlin.coroutines.CoroutineContext
- @ExperimentalCoroutinesApi
- @InternalCoroutinesApi
- actual val eLooperDispatcher:CoroutineDispatcher = object:CoroutineDispatcher(), Delay {
- private val f:(Double)->Unit = ::loop
- private var blocks = mutableListOf<Runnable>()
- private var delay = mutableListOf<Pair<Double, CancellableContinuation<Unit>>>()
- private var invokes = mutableListOf<Pair<Double, Runnable>>()
- init{window.requestAnimationFrame(f)}
- fun loop(c:Double){
- val size = blocks.size
- if(size > 0) blocks.removeAt(size - 1).run()
- var i = delay.size
- while(i-- > 0){
- if(delay[i].first >= c){
- with(delay[i].second){resumeUndispatched(Unit)}
- delay.removeAt(i)
- }
- }
- i = invokes.size
- while(i-- > 0){
- if(invokes[i].first >= c){
- invokes[i].second.run()
- invokes.removeAt(i)
- }
- }
- window.requestAnimationFrame(f)
- }
- override fun dispatch(context:CoroutineContext, block:Runnable){
- blocks.add(block)
- }
- override fun scheduleResumeAfterDelay(timeMillis: Long, continuation:CancellableContinuation<Unit>) {
- delay.add(timeMillis.toDouble() + window.performance.now() to continuation)
- }
- override fun invokeOnTimeout(timeMillis: Long, block:Runnable):DisposableHandle {
- invokes.add(timeMillis.toDouble() + window.performance.now() to block)
- return object:DisposableHandle{override fun dispose(){}}
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement