From e80b16d0a42e9864646abb512f6acf53b732f0a7 Mon Sep 17 00:00:00 2001 From: Jakob K Date: Thu, 20 May 2021 17:11:22 +0200 Subject: [PATCH] Add a mcSyncLaunch extension function --- .../axay/fabrik/core/task/CoroutineTask.kt | 14 -------- .../axay/fabrik/core/task/MinecraftSync.kt | 36 +++++++++++++++++++ 2 files changed, 36 insertions(+), 14 deletions(-) create mode 100644 fabrikmc-core/src/main/kotlin/net/axay/fabrik/core/task/MinecraftSync.kt diff --git a/fabrikmc-core/src/main/kotlin/net/axay/fabrik/core/task/CoroutineTask.kt b/fabrikmc-core/src/main/kotlin/net/axay/fabrik/core/task/CoroutineTask.kt index 3e6fb25c..1a879d36 100644 --- a/fabrikmc-core/src/main/kotlin/net/axay/fabrik/core/task/CoroutineTask.kt +++ b/fabrikmc-core/src/main/kotlin/net/axay/fabrik/core/task/CoroutineTask.kt @@ -2,20 +2,6 @@ package net.axay.fabrik.core.task import kotlinx.coroutines.* -/** - * A [CoroutineDispatcher] which executes code synchronously to the - * MinecraftServer main thread. - */ -lateinit var mcCoroutineDispatcher: CoroutineDispatcher - internal set - -/** - * A [CoroutineScope] using the current MinecraftServer - * as the Dispatcher. - */ -lateinit var mcCoroutineScope: CoroutineScope - internal set - /** * A CoroutineScope using the IO Dispatcher * of kotlinx.coroutines. diff --git a/fabrikmc-core/src/main/kotlin/net/axay/fabrik/core/task/MinecraftSync.kt b/fabrikmc-core/src/main/kotlin/net/axay/fabrik/core/task/MinecraftSync.kt new file mode 100644 index 00000000..5ec804e3 --- /dev/null +++ b/fabrikmc-core/src/main/kotlin/net/axay/fabrik/core/task/MinecraftSync.kt @@ -0,0 +1,36 @@ +package net.axay.fabrik.core.task + +import kotlinx.coroutines.CoroutineDispatcher +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.launch + +/** + * A [CoroutineDispatcher] which executes code synchronously to the + * MinecraftServer main thread. + */ +lateinit var mcCoroutineDispatcher: CoroutineDispatcher + internal set + +/** + * A [CoroutineScope] using the current MinecraftServer + * as the Dispatcher. + */ +lateinit var mcCoroutineScope: CoroutineScope + internal set + +/** + * Does the same as [launch], but the dispatcher defaults to [mcCoroutineDispatcher]. + * + * This way, you can execute code synchronously (to the MinecraftServer main thread) + * very easily. + * + * ```kotlin + * coroutineScope { + * mcSyncLaunch { + * // suspending and sync now + * } + * } + * ``` + */ +fun CoroutineScope.mcSyncLaunch(block: suspend CoroutineScope.() -> Unit) = + launch(mcCoroutineDispatcher, block = block)