Skip to content

Instantly share code, notes, and snippets.

@XiaoGeNintendo
Created November 20, 2023 14:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save XiaoGeNintendo/6cf7d6e09d16da70c310a08de1e65a57 to your computer and use it in GitHub Desktop.
Save XiaoGeNintendo/6cf7d6e09d16da70c310a08de1e65a57 to your computer and use it in GitHub Desktop.
Coroutine Kotlin Example in PLP Essay
import kotlinx.coroutines.*
import java.lang.RuntimeException
import kotlin.coroutines.CoroutineContext
class Enemy
fun addEnemy(enemy: Enemy){
println("Added enemy!!")
}
object CoroutineTaskDispatcher : MainCoroutineDispatcher() {
override val immediate: MainCoroutineDispatcher = this
private val map = HashMap<CoroutineContext, Runnable>()
fun tick(job: Job) {
if(!job.isCompleted){
map[job]!!.run()
}
if (job.isCancelled && map.contains(job)) {
throw RuntimeException("CoroutineTask failed")
}
}
fun remove(job: Job) {
map.remove(job)
}
override fun dispatch(context: CoroutineContext, block: Runnable) {
map[context.job] = block
}
}
suspend fun wait(frame:Int) = repeat(frame) { yield() }
suspend fun task(){
repeat(10){
wait(120)
val enemy=Enemy()
addEnemy(enemy)
}
}
var job:Job?=null
fun onTick(){
if(job==null) {
job=CoroutineScope(CoroutineTaskDispatcher).launch {
task()
}
}
CoroutineTaskDispatcher.tick(job!!)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment