Advertisement
Guest User

Untitled

a guest
Sep 20th, 2019
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.60 KB | None | 0 0
  1. package ein.core.coroutine
  2.  
  3. import kotlinx.coroutines.*
  4. import kotlin.browser.window
  5. import kotlin.coroutines.CoroutineContext
  6.  
  7. @ExperimentalCoroutinesApi
  8. @InternalCoroutinesApi
  9. actual val eLooperDispatcher:CoroutineDispatcher = object:CoroutineDispatcher(), Delay {
  10. private val f:(Double)->Unit = ::loop
  11. private var blocks = mutableListOf<Runnable>()
  12. private var delay = mutableListOf<Pair<Double, CancellableContinuation<Unit>>>()
  13. private var invokes = mutableListOf<Pair<Double, Runnable>>()
  14. init{window.requestAnimationFrame(f)}
  15. fun loop(c:Double){
  16. val size = blocks.size
  17. if(size > 0) blocks.removeAt(size - 1).run()
  18. var i = delay.size
  19. while(i-- > 0){
  20. if(delay[i].first >= c){
  21. with(delay[i].second){resumeUndispatched(Unit)}
  22. delay.removeAt(i)
  23. }
  24. }
  25. i = invokes.size
  26. while(i-- > 0){
  27. if(invokes[i].first >= c){
  28. invokes[i].second.run()
  29. invokes.removeAt(i)
  30. }
  31. }
  32. window.requestAnimationFrame(f)
  33. }
  34. override fun dispatch(context:CoroutineContext, block:Runnable){
  35. blocks.add(block)
  36. }
  37. override fun scheduleResumeAfterDelay(timeMillis: Long, continuation:CancellableContinuation<Unit>) {
  38. delay.add(timeMillis.toDouble() + window.performance.now() to continuation)
  39. }
  40. override fun invokeOnTimeout(timeMillis: Long, block:Runnable):DisposableHandle {
  41. invokes.add(timeMillis.toDouble() + window.performance.now() to block)
  42. return object:DisposableHandle{override fun dispose(){}}
  43. }
  44. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement