### Basic Coroutine Launch Example
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/installation/index.html
Demonstrates how to launch a coroutine within the `onEnable()` function of a Minecraft plugin using the MCCoroutine library.
```kotlin
override fun onEnable() {
// Launch a coroutine here
launch {
// Your coroutine code
}
}
```
--------------------------------
### Testing Plugin with launch{}
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Demonstrates how to test the MCCoroutine integration by calling the `launch{}` coroutine builder within the `onEnable()` function of a Plugin class.
```kotlin
launch {
// Your coroutine code here
}
```
--------------------------------
### Add MCCoroutine Bukkit Dependencies
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Includes the MCCoroutine API and core libraries for Bukkit projects. These are essential for using MCCoroutine functionalities within a Bukkit environment.
```groovy
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-bukkit-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-bukkit-core:2.22.0")
}
```
--------------------------------
### Folia Plugin Libraries for Shading
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Specifies the MCCoroutine libraries to be included in the plugin.yml for Folia servers when shading dependencies.
```yaml
libraries:
- com.github.shynixn.mccoroutine:mccoroutine-folia-api:2.22.0
- com.github.shynixn.mccoroutine:mccoroutine-folia-core:2.22.0
```
--------------------------------
### Bukkit Server Plugin Libraries for Shading
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Specifies the MCCoroutine libraries to be included in the plugin.yml for Bukkit servers (version 1.17 and later) when shading dependencies.
```yaml
libraries:
- com.github.shynixn.mccoroutine:mccoroutine-bukkit-api:2.22.0
- com.github.shynixn.mccoroutine:mccoroutine-bukkit-core:2.22.0
```
--------------------------------
### Add MCCoroutine Sponge Dependencies
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Includes the MCCoroutine API and core libraries for Sponge projects. These are necessary for implementing coroutine-based features in Sponge plugins.
```groovy
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-sponge-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-sponge-core:2.22.0")
}
```
--------------------------------
### Add MCCoroutine BungeeCord Dependencies
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Includes the MCCoroutine API and core libraries for BungeeCord projects. These are necessary for implementing coroutine-based features in BungeeCord plugins.
```groovy
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-bungeecord-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-bungeecord-core:2.22.0")
}
```
--------------------------------
### Coroutine Launch Example
Source: https://github.com/shynixn/mccoroutine/blob/master/README.md
Demonstrates launching a coroutine within a plugin context, allowing for delayed execution and asynchronous calls.
```kotlin
import kotlinx.coroutines.delay
import com.github.shynixn.mccoroutine.bukkit.launch
// Assuming 'plugin' is an instance of your plugin
fun bar() {
plugin.launch {
delay(1000)
bob()
}
}
private suspend fun bob() {
// Coroutine task
}
```
--------------------------------
### Add MCCoroutine Fabric Dependencies
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Includes the MCCoroutine API and core libraries for Fabric projects. These dependencies enable the use of coroutines within Fabric mods.
```groovy
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-fabric-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-fabric-core:2.22.0")
}
```
--------------------------------
### Create a Test Method
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/unittests/index.html
A basic example of how to create a test method using JUnit 5 in Kotlin. This serves as a starting point for writing your unit tests.
```kotlin
import org.junit.jupiter.api.Test
class MyExampleTest {
@Test
fun testCase01(){
}
}
```
--------------------------------
### Add MCCoroutine Minestom Dependencies
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Includes the MCCoroutine API and core libraries for Minestom projects. These dependencies allow for the use of coroutines in Minestom server implementations.
```groovy
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-minestom-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-minestom-core:2.22.0")
}
```
--------------------------------
### Bukkit Plugin Initialization
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/plugin.md
Example of initializing a SuspendingJavaPlugin and calling asynchronous database operations during plugin enablement.
```kotlin
import com.github.shynixn.mccoroutine.bukkit.SuspendingJavaPlugin
class MCCoroutineSamplePlugin : SuspendingJavaPlugin() {
private val database = Database()
override suspend fun onEnableAsync() {
// Minecraft Main Thread
database.createDbIfNotExist()
}
override suspend fun onDisableAsync() {
}
}
```
--------------------------------
### Add MCCoroutine Folia Dependencies
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Includes the MCCoroutine API and core libraries for Folia projects. These are required for leveraging coroutines in Folia-based Minecraft servers.
```groovy
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-folia-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-folia-core:2.22.0")
}
```
--------------------------------
### Coroutine Launch with Undispatched Start (Bukkit)
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/coroutine.md
Shows how to launch a coroutine with `CoroutineStart.UNDISPATCHED` in Bukkit. This ensures the coroutine starts executing immediately on the current thread before switching contexts.
```kotlin
fun foo() {
plugin.launch(start = CoroutineStart.UNDISPATCHED) {
// This is the same thread before calling plugin.launch
val result = withContext(Dispatchers.IO) {
// Perform operations asynchronously.
"Playxer is Max"
}
// Here we are automatically back on a new random thread on the bungeeCord threadPool.
println(result) // Prints 'Player is Max'
}
}
```
--------------------------------
### Add MCCoroutine Bungeecord Libraries
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/installation/index.html
Includes the MCCoroutine Bungeecord API and core libraries for Bungeecord-based Minecraft servers.
```gradle
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-bungeecord-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-bungeecord-core:2.22.0")
}
```
--------------------------------
### Add MCCoroutine Bukkit Libraries
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/installation/index.html
Includes the MCCoroutine Bukkit API and core libraries for Bukkit-based Minecraft servers.
```gradle
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-bukkit-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-bukkit-core:2.22.0")
}
```
--------------------------------
### Add MCCoroutine Sponge Libraries
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/installation/index.html
Includes the MCCoroutine Sponge API and core libraries for Sponge-based Minecraft servers.
```gradle
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-sponge-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-sponge-core:2.22.0")
}
```
--------------------------------
### Add MCCoroutine Fabric Libraries
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/installation/index.html
Includes the MCCoroutine Fabric API and core libraries for Fabric-based Minecraft servers.
```gradle
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-fabric-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-fabric-core:2.22.0")
}
```
--------------------------------
### Sponge Suspending Listener Example
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/listener/index.html
Shows how to register suspending listeners in a Sponge plugin using the `registerSuspendingListeners` extension method. This enables the use of suspend functions within event handlers, facilitating asynchronous tasks. The example includes plugin setup and event handling for server start and stop.
```kotlin
import com.github.shynixn.mccoroutine.sponge.SuspendingPluginContainer
import com.github.shynixn.mccoroutine.sponge.registerSuspendingListeners
import com.google.inject.Inject
import org.spongepowered.api.Sponge
import org.spongepowered.api.event.Listener
import org.spongepowered.api.event.game.state.GameStartedServerEvent
import org.spongepowered.api.event.game.state.GameStoppingServerEvent
import org.spongepowered.api.plugin.Plugin
import org.spongepowered.api.plugin.PluginContainer
@Plugin(
id = "mccoroutinesample",
name = "MCCoroutineSample",
description = "MCCoroutineSample is sample plugin to use MCCoroutine in Sponge."
)
class MCCoroutineSamplePlugin {
private val database = Database()
@Inject
private lateinit var suspendingPluginContainer: SuspendingPluginContainer
@Inject
private lateinit var pluginContainer : PluginContainer
@Listener
suspend fun onEnable(event: GameStartedServerEvent) {
// Minecraft Main Thread
database.createDbIfNotExist()
Sponge.getEventManager().registerSuspendingListeners(pluginContainer, PlayerDataListener(database))
}
@Listener
suspend fun onDisable(event: GameStoppingServerEvent) {
// Minecraft Main Thread
}
}
```
--------------------------------
### MCCoroutine Project Structure and Navigation
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/coroutine/index.html
This HTML snippet outlines the basic navigation structure for the MCCoroutine project, including links to GitHub, Getting Started, User Guide, and FAQ sections.
```html
GitHub
```
--------------------------------
### MCCoroutine Kotlin Coroutines and Minecraft Plugins Guide
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/coroutine/index.html
This section of the MCCoroutine documentation explains how to use Kotlin Coroutines with Minecraft plugins and mods, referencing the installation guide and introducing core concepts.
```markdown
When starting with [Coroutines in Kotlin](https://kotlinlang.org/docs/coroutines-basics.html), you may wonder how you can use them for minecraft plugins and mods. This guide introduces concepts and a production ready API you can use, to start adding coroutines to your project.
Important
Make sure you have already installed MCCoroutine. See [Installation](/gettingstarted) for details.
```
--------------------------------
### Initialize MCCoroutine
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.minestom/-m-c-coroutine/-companion/index.html
Initializes the MCCoroutine library by setting up the theme based on local storage or OS preference. It also includes a placeholder for toggling the menu and searching the API.
```javascript
var pathToRoot = "../../../../";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode");
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark");
}
} else {
const savedDarkMode = JSON.parse(storage);
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark");
}
}
```
--------------------------------
### Sponge Plugin Initialization
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/plugin.md
Shows how to initialize a Sponge plugin using MCCoroutine, handling server startup and shutdown events asynchronously.
```kotlin
import com.github.shynixn.mccoroutine.sponge.SuspendingPluginContainer
import org.spongepowered.api.event.game.GameStoppingServerEvent
import org.spongepowered.api.event.lifecycle.GameStartedServerEvent
import org.spongepowered.api.event.Listener
import org.spongepowered.plugin.jvm.@Plugin
import javax.inject.Inject
@Plugin(
id = "mccoroutinesample",
name = "MCCoroutineSample",
description = "MCCoroutineSample is sample plugin to use MCCoroutine in Sponge."
)
class MCCoroutineSamplePlugin {
private val database = Database()
@Inject
private lateinit var suspendingPluginContainer: SuspendingPluginContainer
@Listener
suspend fun onEnable(event: GameStartedServerEvent) {
// Minecraft Main Thread
database.createDbIfNotExist()
}
@Listener
suspend fun onDisable(event: GameStoppingServerEvent) {
// Minecraft Main Thread
}
}
```
--------------------------------
### MCCoroutine User Guide Navigation
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/coroutine/index.html
This HTML snippet details the navigation within the MCCoroutine User Guide, linking to various sections such as Introduction, Installation, Kotlin Coroutines, Suspending Plugin, Listeners, Commands, Tasks, Caching, Plugin Disable, Exception Handling, Timings, and Unit-Testing.
```html
```
--------------------------------
### BungeeCord Plugin Initialization
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/plugin.md
Demonstrates initializing a BungeeCord plugin with MCCoroutine, including asynchronous startup and shutdown logic.
```kotlin
import com.github.shynixn.mccoroutine.bungeecord.SuspendingPlugin
class MCCoroutineSamplePlugin : SuspendingPlugin() {
private val database = Database()
override suspend fun onEnableAsync() {
// BungeeCord Startup Thread
database.createDbIfNotExist()
}
override suspend fun onDisableAsync() {
// BungeeCord Shutdown Thread (Not the same as the startup thread)
}
}
```
--------------------------------
### Initial Page Load and Theme Setup
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.bukkit/-suspending-java-plugin/on-load-async.html
This snippet handles the initial loading of the page, switching from 'no-js' to 'js' class, and applying dark mode based on local storage or OS preference.
```javascript
var pathToRoot = "../../../\n";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode")
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
} else {
const savedDarkMode = JSON.parse(storage)
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
}
```
--------------------------------
### launch API Documentation
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.bukkit/launch.html
Documentation for the launch coroutine function, detailing parameters, behavior, and exception handling.
```APIDOC
launch
======
fun .[launch](launch.html)(context: [CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.coroutines/-coroutine-context/index.html) = minecraftDispatcher, start: = CoroutineStart.DEFAULT, block: suspend .() -> [Unit](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin-stdlib/kotlin/-unit/index.html)):
Launches a new coroutine on the minecraft main thread without blocking the current thread and returns a reference to the coroutine as a Job. The coroutine is cancelled when the resulting job is Job.cancel.
The coroutine context is inherited from a Plugin.scope. Additional context elements can be specified with [context](launch.html) argument. If the context does not have any dispatcher nor any other [ContinuationInterceptor](https://kotlin.org/api/latest/jvm/stdlib/kotlin-stdlib/kotlin.coroutines/-continuation-interceptor/index.html), then Plugin.minecraftDispatcher is used. The parent job is inherited from a Plugin.scope as well, but it can also be overridden with a corresponding [context](launch.html) element.
By default, the coroutine is immediately scheduled for execution if the current thread is already the minecraft server thread. If the current thread is not the minecraft server thread, the coroutine is moved to the org.bukkit.scheduler.BukkitScheduler and executed in the next server tick schedule. Other start options can be specified via `start` parameter. See CoroutineStart for details. An optional [start](launch.html) parameter can be set to CoroutineStart.LAZY to start coroutine _lazily_. In this case, the coroutine Job is created in _new_ state. It can be explicitly started with Job.start function and will be started implicitly on the first invocation of Job.join.
Uncaught exceptions in this coroutine do not cancel the parent job or any other child jobs. All uncaught exceptions are logged to Plugin.getLogger by default.
#### Parameters
context
The coroutine context to start. Should almost be always be Plugin.minecraftDispatcher. Async operations should be be created using withContext after using the default parameters of this method.
start
coroutine start option. The default value is CoroutineStart.DEFAULT.
block
the coroutine code which will be invoked in the context of the provided scope.
```
--------------------------------
### MCCoroutine Initialization and Theme Toggle
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.bukkit/-m-c-coroutine/index.html
Initializes the MCCoroutine project by setting the path to the root, replacing 'no-js' with 'js' in the document class list, and handling dark mode preferences from local storage or OS settings.
```javascript
var pathToRoot = "../../../\n";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode")
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
} else {
const savedDarkMode = JSON.parse(storage)
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
}
```
--------------------------------
### MCCoroutine Initialization and Theme Handling
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/404.html
This JavaScript code snippet initializes MCCoroutine by retrieving theme preferences from local storage and applying them to the document body. It also handles the initial setup for theme switching based on the user's color scheme preference.
```javascript
var palette = __md_get("__palette");
if (palette && palette.color) {
if ("(prefers-color-scheme)" === palette.color.media) {
var media = matchMedia("(prefers-color-scheme: light)");
var input = document.querySelector(media.matches ? "[data-md-color-media='(prefers-color-scheme: light)']" : "[data-md-color-media='(prefers-color-scheme: dark)']");
palette.color.media = input.getAttribute("data-md-color-media");
palette.color.scheme = input.getAttribute("data-md-color-scheme");
palette.color.primary = input.getAttribute("data-md-color-primary");
palette.color.accent = input.getAttribute("data-md-color-accent");
}
for (var [key, value] of Object.entries(palette.color)) {
document.body.setAttribute("data-md-color-" + key, value);
}
}
```
--------------------------------
### MCCoroutine Test Setup and Usage
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/unittests/index.html
This Kotlin code snippet demonstrates how to set up MCCoroutine for testing. It switches the driver to a test implementation, mocks a plugin using Mockito, and executes coroutines using `runBlocking` with different dispatchers (`minecraftDispatcher`, `IO`, `asyncDispatcher`). It also shows how to use `plugin.launch` and `join()` for concurrent operations.
```kotlin
import org.junit.jupiter.api.Test
import org.mockito.Mockito
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.bukkit.plugin.Plugin
import kotlinx.coroutines.Dispatchers
// Assuming MCCoroutine and TestMCCoroutine are defined elsewhere
// import com.yourpackage.MCCoroutine
// import com.yourpackage.TestMCCoroutine
class MyExampleTest {
init {
/**
* This switches MCCoroutine to the test implementation of MCCoroutine.
* It affects all the tests in the current session.
*/
// MCCoroutine.Driver = TestMCCoroutine.Driver
}
@Test
fun testCase01() {
// Uses the mocking library called Mockito to mock a plugin instance.
// It does not matter how you create a plugin instance. Other mocking libraries work as well.
val plugin = Mockito.mock(Plugin::class.java)
// We need to use runBlocking here, otherwise the test exits early
runBlocking(plugin.minecraftDispatcher) {
println("Step 1: " + Thread.currentThread().name + "/" + Thread.currentThread().id)
withContext(Dispatchers.IO) {
println("Step 2: " + Thread.currentThread().name + "/" + Thread.currentThread().id)
delay(1000)
}
println("Step 3: " + Thread.currentThread().name + "/" + Thread.currentThread().id)
// As always, prefer using Dispatchers.IO instead of plugin.asyncDispatcher.
withContext(plugin.asyncDispatcher) {
println("Step 4: " + Thread.currentThread().name + "/" + Thread.currentThread().id)
delay(1000)
}
println("Step 5: " + Thread.currentThread().name + "/" + Thread.currentThread().id)
// Just as an example, we can also use plugin.launch
plugin.launch {
println("Step 6: " + Thread.currentThread().name + "/" + Thread.currentThread().id)
delay(1000)
println("Step 7: " + Thread.currentThread().name + "/" + Thread.currentThread().id)
}.join() // Wait until finished.
}
}
}
```
--------------------------------
### MCCoroutine Configuration
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.bukkit/index.html
Retrieves the configuration instance for MCCoroutine.
```APIDOC
MCCoroutineConfiguration:
get(): MCCoroutineConfiguration
Description: Gets the configuration instance of MCCoroutine.
Returns: The MCCoroutineConfiguration instance.
```
--------------------------------
### JavaScript Initialization and Theme Toggle
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.velocity/-m-c-coroutine/setup-coroutine-session.html
Initializes the page by replacing 'no-js' with 'js' and sets the theme based on local storage or OS preference.
```javascript
var pathToRoot = "../../../";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode")
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
} else {
const savedDarkMode = JSON.parse(storage)
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
}
```
--------------------------------
### Add MCCoroutine Velocity Dependencies
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Includes the MCCoroutine API and core libraries for Velocity projects. These dependencies enable the use of coroutines within Velocity proxy plugins.
```groovy
dependencies {
implementation("com.github.shynixn.mccoroutine:mccoroutine-velocity-api:2.22.0")
implementation("com.github.shynixn.mccoroutine:mccoroutine-velocity-core:2.22.0")
}
```
--------------------------------
### Initialize Theme and Path
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.fabric/-m-c-coroutine-exception-event/-companion/index.html
Initializes the document's theme based on local storage or OS preference and sets the path to the root directory.
```javascript
var pathToRoot = "../../../../";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode");
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark");
}
} else {
const savedDarkMode = JSON.parse(storage);
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark");
}
}
```
--------------------------------
### Add Kotlin Coroutines Core Dependency
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/installation.md
Adds the core Kotlin Coroutines library, which is required for using coroutine functionalities. It's recommended to use the latest version.
```groovy
dependencies {
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.x.x")
}
```
--------------------------------
### Minigame Countdown Example
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/tasks/index.html
Provides a Kotlin `MiniGame` class with a `start` function that implements a countdown using a `for` loop and `delay`. It sends messages to players during the countdown.
```kotlin
import kotlinx.coroutines.delay
import org.bukkit.entity.Player
class MiniGame {
private var isStarted = false;
private var players = HashSet()
fun join(player: Player) {
if (isStarted) {
return
}
players.add(player)
}
suspend fun start() {
if (isStarted) {
return
}
isStarted = true
// This loop represents a traditional repeating task which ticks every 1 second and is called 20 times.
for (i in 0 until 20) {
sendMessageToPlayers("Game is starting in ${20 - i} seconds.")
delay(1000)
}
// ... Teleport players to game.
}
private fun sendMessageToPlayers(message: String) {
players.forEach { p -> p.sendMessage(message) }
}
}
```
--------------------------------
### Page Redirection Example
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/index.html
This snippet demonstrates how to redirect the browser to an API documentation index page using JavaScript. It's a common pattern for guiding users to relevant documentation.
```javascript
window.location.href = "apidocs/index.html";
```
--------------------------------
### Theme Toggling and Initialization Script
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.bukkit/-m-c-coroutine-exception-event/-companion/index.html
This script handles the initial setup of the page, including toggling between light and dark themes based on user preferences or local storage. It also initializes the 'js' class on the document element.
```javascript
var pathToRoot = "../../../../";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode")
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
} else {
const savedDarkMode = JSON.parse(storage)
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
}
```
--------------------------------
### Starting Coroutine on Bukkit
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/coroutine/index.html
Launches a coroutine on the Minecraft main thread for Bukkit servers. This is the standard way to start coroutines in Bukkit plugins.
```kotlin
import com.github.shynixn.mccoroutine.bukkit.launch
import org.bukkit.plugin.Plugin
fun foo() {
plugin.launch {
// This will always be on the minecraft main thread.
// If you have been on the minecraft main thread before calling plugin.launch, this scope is entered immediately without any delay.
}
}
```
--------------------------------
### Plugin Initialization and Dark Mode Handling
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.bukkit/-suspending-java-plugin/on-enable.html
This snippet demonstrates the initial setup when a plugin is enabled. It includes logic to set the 'js' class on the document element and to apply dark mode based on local storage settings or operating system preferences.
```javascript
var pathToRoot = "../../../\n";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode")
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
} else {
const savedDarkMode = JSON.parse(storage)
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
}
```
--------------------------------
### Basic Coroutine Launch (Bukkit)
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/docs/coroutine.md
Demonstrates launching a coroutine with default settings in a Bukkit environment. The code block inside `withContext` is executed on the IO dispatcher, and the result is printed back on the main thread.
```kotlin
fun foo() {
plugin.launch {
// This is the same thread before calling plugin.launch
val result = withContext(Dispatchers.IO) {
// Perform operations asynchronously.
"Player is Max"
}
// Here we are automatically back on a new random thread on the bungeeCord threadPool.
println(result) // Prints 'Player is Max'
}
}
```
--------------------------------
### MCCoroutine Minestom Example (Kotlin)
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/plugin/index.html
An example of integrating MCCoroutine with a Minestom server. It shows how to launch coroutines within the Minestom server's lifecycle for asynchronous tasks.
```kotlin
import com.github.shynixn.mccoroutine.minestom.launch
import net.minestom.server.MinecraftServer
fun main(args: Array) {
val minecraftServer = MinecraftServer.init()
minecraftServer.launch {
// Minecraft Main Thread
val database = Database()
database.createDbIfNotExist()
}
minecraftServer.start("0.0.0.0", 25565)
}
```
--------------------------------
### MCCoroutine Fabric Server Mod Example (Kotlin)
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/plugin/index.html
Provides an example of integrating MCCoroutine with a Fabric server mod. It shows how to hook into server lifecycle events and manage coroutines for asynchronous tasks.
```kotlin
import com.github.shynixn.mccoroutine.fabric.MCCoroutineConfiguration
import com.github.shynixn.mccoroutine.fabric.launch
import net.fabricmc.api.DedicatedServerModInitializer
import net.fabricmc.fabric.api.event.lifecycle.v1.ServerLifecycleEvents
import net.minecraft.server.MinecraftServer
import java.util.concurrent.Executor
class MCCoroutineSampleServerMod : DedicatedServerModInitializer {
override fun onInitializeServer() {
ServerLifecycleEvents.SERVER_STARTING.register(ServerLifecycleEvents.ServerStarting { server ->
// Connect Native Minecraft Scheduler and MCCoroutine.
MCCoroutineConfiguration.minecraftExecutor = Executor { r ->
server.submitAndJoin(r)
}
launch {
onServerStarting(server)
}
})
ServerLifecycleEvents.SERVER_STOPPING.register { server ->
MCCoroutineConfiguration.disposePluginSession()
}
}
/**
* MCCoroutine is ready after the server has started.
*/
private suspend fun onServerStarting(server : MinecraftServer) {
// Minecraft Main Thread
val database = Database()
database.createDbIfNotExist()
}
}
```
--------------------------------
### Project Configuration
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/index.html
This JSON object outlines the project's configuration, including its base directory, enabled features, search worker script, and internationalization (i18n) translations for various UI elements.
```json
{
"base": ".",
"features": [
"navigation.instant",
"navigation.tabs",
"content.tabs.link",
"content.code.copy",
"navigation.footer"
],
"search": "assets/javascripts/workers/search.f8cc74c7.min.js",
"tags": null,
"translations": {
"clipboard.copied": "Copied to clipboard",
"clipboard.copy": "Copy to clipboard",
"search.result.more.one": "1 more on this page",
"search.result.more.other": "# more on this page",
"search.result.none": "No matching documents",
"search.result.one": "1 matching document",
"search.result.other": "# matching documents",
"search.result.placeholder": "Type to start searching",
"search.result.term.missing": "Missing",
"select.version": "Select version"
},
"version": null
}
```
--------------------------------
### launch Coroutine
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.sponge/launch.html
Launches a new coroutine on the minecraft main thread without blocking the current thread. The coroutine is cancelled when the resulting job is Job.cancel. The coroutine context is inherited from a PluginContainer.scope. Additional context elements can be specified with the 'context' argument. If the context does not have any dispatcher or any other ContinuationInterceptor, then Plugin.minecraftDispatcher is used. The parent job is inherited from a PluginContainer.scope as well, but it can also be overridden with a corresponding 'context' element. By default, the coroutine is immediately scheduled for execution if the current thread is already the minecraft server thread. If the current thread is not the minecraft server thread, the coroutine is moved to the org.bukkit.scheduler.BukkitScheduler and executed in the next server tick schedule. Other start options can be specified via the `start` parameter. See CoroutineStart for details. An optional `start` parameter can be set to CoroutineStart.LAZY to start the coroutine lazily. In this case, the coroutine Job is created in a `new` state. It can be explicitly started with Job.start function and will be started implicitly on the first invocation of Job.join. Uncaught exceptions in this coroutine do not cancel the parent job or any other child jobs. All uncaught exceptions are logged to a customer logger by default.
```APIDOC
launch
======
fun .[launch](launch.html)(context: [CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin-stdlib/kotlin.coroutines/-coroutine-context/index.html) = minecraftDispatcher, start: = CoroutineStart.DEFAULT, block: suspend .() -> [Unit](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin-stdlib/kotlin/-unit/index.html)):
Launches a new coroutine on the minecraft main thread without blocking the current thread and returns a reference to the coroutine as a Job. The coroutine is cancelled when the resulting job is Job.cancel.
The coroutine context is inherited from a PluginContainer.scope. Additional context elements can be specified with [context](launch.html) argument. If the context does not have any dispatcher nor any other [ContinuationInterceptor](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin-stdlib/kotlin.coroutines/-continuation-interceptor/index.html), then Plugin.minecraftDispatcher is used. The parent job is inherited from a PluginContainer.scope as well, but it can also be overridden with a corresponding [context](launch.html) element.
By default, the coroutine is immediately scheduled for execution if the current thread is already the minecraft server thread. If the current thread is not the minecraft server thread, the coroutine is moved to the org.bukkit.scheduler.BukkitScheduler and executed in the next server tick schedule. Other start options can be specified via `start` parameter. See CoroutineStart for details. An optional [start](launch.html) parameter can be set to CoroutineStart.LAZY to start coroutine _lazily_. In this case, the coroutine Job is created in _new_ state. It can be explicitly started with Job.start function and will be started implicitly on the first invocation of Job.join.
Uncaught exceptions in this coroutine do not cancel the parent job or any other child jobs. All uncaught exceptions are logged to a customer logger by default.
#### Parameters
context
The coroutine context to start. Should almost be always be Plugin.minecraftDispatcher. Async operations should be be created using withContext after using the default parameters of this method.
start
coroutine start option. The default value is CoroutineStart.DEFAULT.
block
the coroutine code which will be invoked in the context of the provided scope.
```
--------------------------------
### Bukkit PlayerJoinEvent Example
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/coroutine/index.html
An example of launching a coroutine within a Bukkit PlayerJoinEvent handler. It performs an asynchronous file read operation using Dispatchers.IO and then updates the player on the main thread.
```kotlin
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.bukkit.event.EventHandler
import org.bukkit.event.player.PlayerJoinEvent
import java.nio.file.Paths
import java.nio.file.Files
// Assuming 'plugin' is an instance of your Bukkit plugin class with launch scope
// @EventHandler
// fun onPlayerJoinEvent(event: PlayerJoinEvent) {
// plugin.launch {
// // This will always be on the minecraft main thread.
// val name = event.player.name
// val listOfFriends = withContext(Dispatchers.IO) {
// // IO Thread
// val friendNames = Files.readAllLines(Paths.get("$name.txt"))
// friendNames
// }
//
// // Main Thread
// val friendText = listOfFriends.joinToString(", ")
// event.player.sendMessage("My friends are: $friendText")
// }
// }
```
--------------------------------
### Initialize MCCoroutine
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.fabric/-m-c-coroutine/-companion/index.html
Initializes the MCCoroutine library by setting up the theme based on local storage or OS preference. It also replaces 'no-js' with 'js' class on the document element.
```javascript
var pathToRoot = "../../../../";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode")
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
} else {
const savedDarkMode = JSON.parse(storage)
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
}
```
--------------------------------
### MCCoroutine User Guide Table of Contents
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/wiki/site/coroutine/index.html
This HTML snippet presents the table of contents for the MCCoroutine User Guide, listing key sections related to Kotlin Coroutines and Minecraft plugins.
```html
```
--------------------------------
### Initialize MCCoroutine Driver
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.bukkit/-m-c-coroutine/-companion/-driver.html
Initializes the MCCoroutine driver by checking local storage for theme preferences and applying the dark theme if necessary. It also replaces 'no-js' with 'js' in the document's class list.
```javascript
var pathToRoot = "../../../../";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode")
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
} else {
const savedDarkMode = JSON.parse(storage)
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark")
}
}
```
--------------------------------
### launch Coroutine
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.minestom/launch.html
Launches a new coroutine on the minecraft main thread without blocking the current thread and returns a reference to the coroutine as a Job. The coroutine is cancelled when the resulting job is Job.cancel. The coroutine context is inherited from a scope. Additional context elements can be specified with context argument. If the context does not have any dispatcher nor any other ContinuationInterceptor, then minecraftDispatcher is used. The parent job is inherited from a scope as well, but it can also be overridden with a corresponding context element. By default, the coroutine is immediately scheduled for execution if the current thread is already the minecraft server thread. If the current thread is not the minecraft server thread, the coroutine is moved to the net.minestom.server.timer.Scheduler and executed in the next server tick schedule. Other start options can be specified via `start` parameter. See CoroutineStart for details. An optional `start` parameter can be set to CoroutineStart.LAZY to start coroutine _lazily_. In this case, the coroutine Job is created in _new_ state. It can be explicitly started with Job.start function and will be started implicitly on the first invocation of Job.join. Uncaught exceptions in this coroutine do not cancel the parent job or any other child jobs. All uncaught exceptions are logged to extension or server logger by default.
```APIDOC
launch
======
fun .[launch](launch.html)(context: [CoroutineContext](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin-stdlib/kotlin.coroutines/-coroutine-context/index.html) = minecraftDispatcher, start: = CoroutineStart.DEFAULT, block: suspend .() -> [Unit](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin-stdlib/kotlin/-unit/index.html)):
Launches a new coroutine on the minecraft main thread without blocking the current thread and returns a reference to the coroutine as a Job. The coroutine is cancelled when the resulting job is Job.cancel.
The coroutine context is inherited from a [scope](scope.html). Additional context elements can be specified with [context](launch.html) argument. If the context does not have any dispatcher nor any other [ContinuationInterceptor](https://kotlinlang.org/api/latest/jvm/stdlib/kotlin-stdlib/kotlin.coroutines/-continuation-interceptor/index.html), then [minecraftDispatcher](minecraft-dispatcher.html) is used. The parent job is inherited from a [scope](scope.html) as well, but it can also be overridden with a corresponding [context](launch.html) element.
By default, the coroutine is immediately scheduled for execution if the current thread is already the minecraft server thread. If the current thread is not the minecraft server thread, the coroutine is moved to the net.minestom.server.timer.Scheduler and executed in the next server tick schedule. Other start options can be specified via `start` parameter. See CoroutineStart for details. An optional [start](launch.html) parameter can be set to CoroutineStart.LAZY to start coroutine _lazily_. In this case, the coroutine Job is created in _new_ state. It can be explicitly started with Job.start function and will be started implicitly on the first invocation of Job.join.
Uncaught exceptions in this coroutine do not cancel the parent job or any other child jobs. All uncaught exceptions are logged to extension or server logger by default.
#### Parameters
context
The coroutine context to start. Should almost be always be [minecraftDispatcher](minecraft-dispatcher.html). Async operations should be be created using withContext after using the default parameters of this method.
start
coroutine start option. The default value is CoroutineStart.DEFAULT.
block
the coroutine code which will be invoked in the context of the provided scope.
```
--------------------------------
### Initial Page Setup and Dark Mode Toggle
Source: https://github.com/shynixn/mccoroutine/blob/master/docs/apidocs/mccoroutine-root/com.github.shynixn.mccoroutine.bungeecord/-suspending-command/permission-message.html
This snippet handles the initial setup of the web page, replacing 'no-js' with 'js' and managing the dark mode preference based on local storage or OS settings.
```javascript
var pathToRoot = "../../../";
document.documentElement.classList.replace("no-js","js");
const storage = localStorage.getItem("dokka-dark-mode");
if (storage == null) {
const osDarkSchemePreferred = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;
if (osDarkSchemePreferred === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark");
}
} else {
const savedDarkMode = JSON.parse(storage);
if(savedDarkMode === true) {
document.getElementsByTagName("html")[0].classList.add("theme-dark");
}
}
```