summaryrefslogtreecommitdiff
path: root/src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt
blob: b1d18ab9f93ca1cd7a6a7e3c4b4985e4574fb095 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
package io.dico.parcels2.util

import kotlinx.coroutines.CoroutineDispatcher
import kotlinx.coroutines.Runnable
import org.bukkit.plugin.Plugin
import kotlin.coroutines.CoroutineContext

abstract class MainThreadDispatcher : CoroutineDispatcher() {
    abstract val mainThread: Thread
    abstract fun runOnMainThread(task: Runnable)
}

@Suppress("FunctionName")
fun MainThreadDispatcher(plugin: Plugin): MainThreadDispatcher {
    return object : MainThreadDispatcher() {
        override val mainThread: Thread = Thread.currentThread()

        override fun dispatch(context: CoroutineContext, block: Runnable) {
            doDispatch(block)
        }

        override  fun runOnMainThread(task: Runnable) {
            doDispatch(task)
        }

        private fun doDispatch(task: Runnable) {
            if (Thread.currentThread() === mainThread) task.run()
            else plugin.server.scheduler.runTaskLater(plugin, task, 0)
        }
    }
}