Created
November 20, 2023 14:46
-
-
Save XiaoGeNintendo/6cf7d6e09d16da70c310a08de1e65a57 to your computer and use it in GitHub Desktop.
Coroutine Kotlin Example in PLP Essay
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
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