Coroutine for Bukkit

Overview

Heartbeat Coroutines

Kotlin Kotlin Gradle Gradle Maven Central GitHub Kotlin

두근두근 ❤️ 코루틴

Coroutine for Paper


  • Features

    • Bukkit의 mainHeartBeat(GameLoop)에서 dispatch되는 Coroutine
    • JavaPlugin 생명주기의 CoroutineScope
    • 유연한 지연작업

GameLoop 내에서 병렬 혹은 비동기 라이브러리 없이 다음 연쇄 작업을 처리하는 코드를 작성해보겠습니다.

  1. 3초간 1초마다 카운트다운 메시지를 방송
  2. 5초간 1초마다 모든 개체에게 데미지
  3. 서프라이즈~ 메시지를 방송 후 종료 악질 운영자

Thread

Runnable {
    repeat(3) {
        // 비동기 문제를 해결하기 위해 GameLoop의 Thread에서 호출 
        GameLoop.runLater {
            broadcast(3 - it)
            Thread.sleep(1000L)
        }
    }
    repeat(5) {
        GameLoop.runLater {
            damageAll()
        }
        Thread.sleep(1000L)
    }
    GameLoop.runLater {
        broadcast("surprise~")
    }
}.let {
    Thread(it).start()
}

Callback

// 비동기로 어디선가 실행해주는 함수
async({
    repeat(3) {
        GameLoop.runLater {
            broadcast(3 - it)
            Thread.sleep(1000L)
        }
    }
}) {
    async({
        repeat(5) {
            GameLoop.runLater {
                damageAll()
            }
            Thread.sleep(1000L)
        }
    }) {
        async {
            GameLoop.runLater {
                broadcast("surprise~")
            }
        }
    }
}

FSM

// 취소 가능한 태스크
class Surprise : GameLoopTask() {
    private var state = 0
    private var countdownTicks = 0
    private var damageTicks = 0

    // 1초마다 GameLoop 에서 호출
    override fun run() {
        when (state) {
            0 -> {
                val message = 3 - countdownTicks++
                broadcast(message)

                if (countdownTicks >= 3) state = 1
            }
            1 -> {
                damageAll()

                if (++damageTicks >= 5) state = 2
            }
            else -> {
                broadcast("surprise~")
                cancel()
            }
        }
    }
}

극단적인 예를 들었습니다만..

실제로 GameLoop내에서 연쇄, 순차적인 루틴을 처리하기 위해선 대부분 위 예제들과 같은 구조의 코드를 작성하게됩니다.

루틴이 복잡해질수록 비동기 문제, 복잡성으로 인해 유연성은 떨어지고 유지보수 난이도는 기하급수로 상승합니다.

Coroutine을 이용하면 GameLoop 내 연쇄 작업 코드의 복잡성을 획기적으로 줄일 수 있습니다.

아래 예제는 GameLoop내에서 동기적으로 실행되는 Coroutine 코드입니다


Coroutine

// GameLoopDispatcher = GameLoop에서 Coroutine을 실행하는 CoroutineDispatcher 
CoroutineScope(GameLoopDispatcher).launch {
    repeat(3) {
        broadcast(3 - it)
        delay(1000L)
    }
    repeat(5) {
        damaegAll()
        delay(1000L)
    }
    brocast("surprise~")
}

Thread의 코드와 비슷하지만 GameLoop 내에서 동기적으로 실행 가능한 코드입니다!

Coroutine의 동작원리는 이 문서 를 참고하세요


Heartbeat coroutines 시작하기

Gradle

repositories {
    mavenCentral()
}
dependencies {
    implementation("io.github.monun:heartbeat-coroutines:<version>")
}

Example

// JavaPlugin#onEnable()
HeartbeatScope().launch {
    val suspension = Suspension()
    repeat(10) {
        logger.info(server.isPrimaryThread)
        suspension.delay(75L)
    }
    logger.info("BOOM")
}

Dispatchers.Heartbeat

JavaPlugin 과 같은 생명주기를 가진 CoroutineDispatcher 입니다.

Coroutine을 Bukkit의 PrimaryThread에서만 실행합니다.


HeartbeatScope()

JavaPlugin 과 같은 생명주기를 가진 CoroutineScope 입니다.

Dispatchers.HeartbeatCoroutineDispatcher로 가지며 JavaPlugin 생명주기를 따라가는 SupervisorJob을 부모로 가집니다.


Suspension

누적 지연 기능을 가진 클래스입니다.

Dispatchers.Hearbeat는 Coroutine을 Bukkit의 PrimaryThread에서 실행하기 위해서 BukkitScheduler#runTask를 사용합니다.

BukkitScheduler는 1tick(50ms)마다 등록된 태스크들을 실행하며 서버 상태에 따라 지연될 수 있습니다.

Coroutine은 지연을 millisecond 단위로 제어 할 수 있으며 이는 Dispatchers.Heartbeat에서 실행될 때 결과가 기대와 다를 수 있습니다.

delay(1) 함수가 호출 될 때 Dispatchers.Heatbeat에서는 50ms 이상 늘어날 수 있습니다.

Suspension은 내부적으로 누적되는 지연 시간을 가지며 누적된 시간이 과거일 경우 yield()를 호출하고 미래일 경우 남은 시간만큼 delay를 호출합니다.

You might also like...
Android Clean Architechture with MVVM, LiveData, Coroutine, Dagger Hilt, Room, DataStore
Android Clean Architechture with MVVM, LiveData, Coroutine, Dagger Hilt, Room, DataStore

MovKu An application that displays a list of popular movies and detail Concepts Tech Stack Kotlin -A modern programming language that makes developers

🧸 A multiplatform coroutine-based wrapper for popular platform-specific Redis client libraries

🧸 rekt ⚠️ WARNING! This project is experimental and may be missing essential features. Please let us know if you found any issues or have any suggest

🧸 A multiplatform coroutine-based wrapper for popular platform-specific Redis client libraries

🧸 rekt ⚠️ WARNING! This project is experimental and may be missing essential features. Please let us know if you found any issues or have any suggest

This Project for how to use  MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture.
This Project for how to use MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture.

Clean-architecture This Project for how to use MVVM , state flow, Retrofit, dagger hit, coroutine , use cases with Clean architecture. Why i should us

A distribution of performance-oriented Bukkit patches that aims to keep stability and vanilla behaviour
A distribution of performance-oriented Bukkit patches that aims to keep stability and vanilla behaviour

Patina A distribution of performance-oriented Bukkit patches that aims to keep stability and vanilla behaviour. You can find explanation of configurat

Simple cron command runner for Bukkit 1.17+

Cron Runner Description / 설명 Simple cron command runner for Bukkit 1.17+ Bukkit 1.17 이상을 위한 간단한 cron 명령어 실행기 입니다. Configuration Guide (config.yml) deb

A small DSL to make building a conversation in Bukkit easy.

Konversation Konversation provides a simple builder to construct chains of prompts to be used in the conversation API present in Bukkit. Bukkit only p

A Unified, Modern and Efficient Bukkit plugin framework

LSPlugin ! WARNING ! This project is still under development DO NOT PUT INTO PRODUCTION ENVIRONMENT 一个专门为了 .DP7 群服务器 Charmless 的定制插件框架。未来Charmless的一切开

Slime World Format implementation written in Kotlin with Zstd for bukkit.

Slime Korld Easily create many slime worlds with the Slime Korld. What is Slime Korld? Slime Korld is a bukkit library written in Kotlin to make minec

Bukkit library written in Kotlin to make with compatibility and ease non-playable-character (NPC)

mc-npk Easy to use, fast and efficient library to make non-playable-characters (

MineJS is a scripting plugin for the Bukkit!

Mine.js(W-I-P) Minecraft Bukkit Scripting with JS by Netherald How to apply? Download Paper or Bungee Version. and put it to plugins folder. Script fo

A Gradle plugin that generates plugin.yml for Bukkit/BungeeCord/Nukkit plugins based on the Gradle project

plugin-yml is a simple Gradle plugin that generates the plugin.yml plugin description file for Bukkit plugins, bungee.yml for Bungee plugins or nukkit.yml for Nukkit plugins based on the Gradle project. Various properties are set automatically (e.g. project name, version or description) and additional properties can be added using a simple DSL.

Download tool based on kotlin and coroutine.
Download tool based on kotlin and coroutine.

DownloadX A multi-threaded download tool written with Coroutine and Kotlin Read this in other languages: 中文, English, Changelog Prepare Add jitpack re

Multiplatform coroutine-based HTTP client wrapper for Kotlin

networkinkt This is a lightweight HTTP client for Kotlin. It relies on coroutines on both JS & JVM platforms. Here is a simple GET request: val text =

BaseDemo 是Android MVVM + Retrofit + OkHttp + Coroutine 协程 + 组件化架构的Android应用开发规范化架构
BaseDemo 是Android MVVM + Retrofit + OkHttp + Coroutine 协程 + 组件化架构的Android应用开发规范化架构

BaseDemo 是Android MVVM + Retrofit + OkHttp + Coroutine 协程 + 组件化架构的Android应用开发规范化架构,通过不断的升级迭代,目前主要分为两个版本,分别为分支 MVVM+Databinding 组件化版本,分支MVVM+Databinding+Single 单体版本。旨在帮助您快速构建属于自己的APP项目架构,做到快速响应上手,另外再长期的实践经验中汇总了大量的使用工具类,主要放在了项目 `lib_common` 组件中,以供大家参考使用。具体使用请开发者工具自己项目需求决定选择如何使用。

MVVM RECIPE ANDROID APP Is an app where I show how to use MVVM, retrofit, dagger hilt, coroutine, liveData, Kotlin, navigation component, and so on...
MVVM RECIPE ANDROID APP Is an app where I show how to use MVVM, retrofit, dagger hilt, coroutine, liveData, Kotlin, navigation component, and so on...

MVVM RECIPE ANDROID APP Is an app where I show how to use MVVM, retrofit, dagger hilt, coroutine, liveData, kotlin, navigation component, and so on...

Android Multi Theme Switch Library ,use  kotlin language ,coroutine ,and so on ...
Android Multi Theme Switch Library ,use kotlin language ,coroutine ,and so on ...

Magic Mistletoe Android多主题(换肤)切换框架 背景 时隔四年,在网易换肤之前的思路下,做了几点改进,现在完全通过反射创建View,并且在SkinLoadManager中提供一个configCustomAttrs以支持自定义View的属性插队替换 摈弃了之前的AsyncTask

The JeTrivia is built on a modern Android Development tech stack with MVVM architecture. Kotlin, Coroutine, Flow, StateFlow, Jetpack Compose, Navigation, Room, Hilt, Retrofit2, OkHttp3, kotlinx.serialization, MockK, Truth
The JeTrivia is built on a modern Android Development tech stack with MVVM architecture. Kotlin, Coroutine, Flow, StateFlow, Jetpack Compose, Navigation, Room, Hilt, Retrofit2, OkHttp3, kotlinx.serialization, MockK, Truth

JeTrivia 🚧 In Progress 🚧 The JeTrivia application is sample based on MVVM architecture. Fetching data from the network via repository pattern and sa

AAC MVVM + Clean Architecture + Coroutine Flow

GithubBrowser MVVM Clean Architecture Sample AAC MVVM + Clean Architecture + Coroutine Flow 본 샘플 프로젝트는 https://github.com/omjoonkim/GitHubBrowserApp 을

Owner
null
A small DSL to make building a conversation in Bukkit easy.

Konversation Konversation provides a simple builder to construct chains of prompts to be used in the conversation API present in Bukkit. Bukkit only p

Tim Hagemann 2 Dec 4, 2022
Slime World Format implementation written in Kotlin with Zstd for bukkit.

Slime Korld Easily create many slime worlds with the Slime Korld. What is Slime Korld? Slime Korld is a bukkit library written in Kotlin to make minec

Luiz Otávio 11 Nov 15, 2022
Download tool based on kotlin and coroutine.

DownloadX A multi-threaded download tool written with Coroutine and Kotlin Read this in other languages: 中文, English, Changelog Prepare Add jitpack re

Season 138 Dec 22, 2022
Kotlin coroutine capable Finite-State Machine (multiplatform)

Comachine Features Kotlin corutines. Event handlers can launch coroutines for collecting external events of performing side effects. Structured concur

Sergej Shafarenka 22 Dec 14, 2022
Kotlin coroutine capable Finite-State Machine (multiplatform)

Comachine Features Kotlin corutines. Event handlers can launch coroutines for collecting external events of performing side effects. Structured concur

Sergej Shafarenka 22 Dec 14, 2022
Kotlin Coroutine için örnek proje

Kotlin Coroutines Kotlin Coroutines: Senkron kod yazarak asenkron uygulamalar geliştirmeye yarayan bir eklentidir. Network istekleri cevap gelene kada

Murat YÜKSEKTEPE 3 Dec 7, 2022
Skeleton project for show the architecture of Android project using MVVM, Clean Architecture and Kotlin coroutine Flow

ClearScoreDemo Skeleton project for showing the architecture of Android project using MVVM, Clean architecture and Kotlin coroutine Flow App Architect

Plabon Modak 1 Mar 6, 2022
Android application showcasing the MVVM architecture, Clean code using Kotlin, Coroutine, Flow and databinding.

Code4Lyst Android application showcasing the MVVM architecture, Clean code using Kotlin, Coroutine, Flow and databinding. App Architecture MVVM CleanC

Plabon Modak 1 Nov 29, 2021
A Gallery app developed using kotlin and MVVM architecture with Coroutine

A Gallery app developed using kotlin and MVVM architecture Loading image from un

Atiar Talukdar 1 Dec 21, 2021
Android - kotlin Coroutine with MVVM and Paging 3

Android - kotlin Coroutine with MVVM and Paging 3 To Loarn more about paging 3 To Loarn more about LoadStateAdapter API Reference Get all items Api So

Haresh 1 Mar 17, 2022