summaryrefslogtreecommitdiff
path: root/src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt
diff options
context:
space:
mode:
authorDico <dico.karssiens@gmail.com>2018-09-23 06:34:03 +0100
committerDico <dico.karssiens@gmail.com>2018-09-23 06:34:03 +0100
commit038e698a1421e95d1dc96117cd9a2ae0cfdddf6a (patch)
tree9a9a44bb20869ab8a7ab2287d14c6558a495614b /src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt
parentf499555f8bff9d3c77340a0aa852cb418e81e6f7 (diff)
Work down some todo items, update to kotlin 1.3-rc
Diffstat (limited to 'src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt')
-rw-r--r--src/main/kotlin/io/dico/parcels2/util/MainThreadDispatcher.kt31
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