diff options
Diffstat (limited to 'src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt')
-rw-r--r-- | src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt b/src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt new file mode 100644 index 0000000..b1d18ab --- /dev/null +++ b/src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt @@ -0,0 +1,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) + } + } +}
\ No newline at end of file |