All Downloads are FREE. Search and download functionalities are using the official Maven repository.

main.dev.schlaubi.lavakord.interop.JavaEventSource.kt Maven / Gradle / Ivy

There is a newer version: 7.1.0
Show newest version
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))
                }
            }
        })
    }
}





© 2015 - 2024 Weber Informatics LLC | Privacy Policy