Last active
May 16, 2025 10:17
-
-
Save Cybermaxke/50188a54130a29e9bd3696f06427cb33 to your computer and use it in GitHub Desktop.
Velocity Event Coroutines - Use kotlin coroutines inside your velocity event handlers.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.velocitypowered.api.event.EventTask | |
import kotlin.coroutines.Continuation | |
import kotlin.coroutines.CoroutineContext | |
import kotlin.coroutines.EmptyCoroutineContext | |
import kotlin.coroutines.startCoroutine | |
fun suspended(fn: suspend () -> Unit): EventTask { | |
return EventTask.withContinuation { continuation -> | |
val completion = object : Continuation<Unit> { | |
override val context: CoroutineContext | |
get() = EmptyCoroutineContext | |
override fun resumeWith(result: Result<Unit>) { | |
if (result.isFailure) { | |
continuation.resumeWithException(result.exceptionOrNull()) | |
} else { | |
continuation.resume() | |
} | |
} | |
} | |
fn.startCoroutine(completion) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.velocitypowered.api.event.Subscribe | |
import com.velocitypowered.api.event.lifecycle.ProxyInitializeEvent | |
import kotlinx.coroutines.Dispatchers | |
import kotlinx.coroutines.delay | |
import kotlinx.coroutines.withContext | |
class TasksTest { | |
@Subscribe | |
fun onInit(event: ProxyInitializeEvent) = suspended { | |
val result = withContext(Dispatchers.IO) { | |
// Do something IO related... | |
delay(100) | |
1 | |
} | |
println("Result: $result") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment