Skip to content

Instantly share code, notes, and snippets.

@Cybermaxke
Last active October 27, 2022 18:27
Show Gist options
  • Save Cybermaxke/50188a54130a29e9bd3696f06427cb33 to your computer and use it in GitHub Desktop.
Save Cybermaxke/50188a54130a29e9bd3696f06427cb33 to your computer and use it in GitHub Desktop.
Velocity Event Coroutines - Use kotlin coroutines inside your velocity event handlers.
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)
}
}
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