main.dev.schlaubi.lavakord.interop.JavaEventSource.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java Show documentation
Show all versions of java Show documentation
Coroutine based client for Lavalink (Kotlin and Java)
package dev.schlaubi.lavakord.interop
import dev.schlaubi.lavakord.audio.EventSource
import kotlinx.coroutines.jdk9.asPublisher
import mu.KotlinLogging
import java.util.concurrent.Flow
import java.util.concurrent.Flow.Subscriber
import java.util.function.Consumer
private val LOG = KotlinLogging.logger { }
/**
* Java equivalent of [EventSource].
*
* @param T the base event type
*
* @property suspendingEventSource the underlying delegate [EventSource]
* @property events All events received using a [Flow.Publisher]
*/
public interface JavaEventSource {
public val suspendingEventSource: EventSource
public val events: Flow.Publisher
get() = suspendingEventSource.events.asPublisher()
/**
* Creates an event handler which executes [Consumer] for every event of [eventType].
*/
public fun on(eventType: Class, handler: Consumer) {
events.subscribe(object : Subscriber {
override fun onSubscribe(subscription: Flow.Subscription) {
subscription.request(Long.MAX_VALUE)
}
override fun onError(throwable: Throwable) {
// This in theory should never happen
LOG.error(throwable) { "An error occurred whilst subscribing to events" }
}
override fun onComplete() = Unit
override fun onNext(item: T) {
if (eventType.isInstance(item)) {
handler.accept(eventType.cast(item))
}
}
})
}
}