Skip to content

Commit

Permalink
Add coroutineScope property to event handlers
Browse files Browse the repository at this point in the history
This allows your event handlers to be launched in a coroutine scope if needed.
  • Loading branch information
gdude2002 committed Jul 9, 2024
1 parent 4bb2696 commit 4575003
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -346,17 +346,17 @@ public open class ExtensibleBot(
*/
public inline fun <reified T : Event> on(
launch: Boolean = true,
scope: CoroutineScope = this.getKoin().get<Kord>(),
scope: CoroutineScope = kordRef,
noinline consumer: suspend T.() -> Unit,
): Job =
events.buffer(Channel.UNLIMITED)
.filterIsInstance<T>()
.onEach {
runCatching {
if (launch) kordRef.launch { consumer(it) } else consumer(it)
if (launch) scope.launch { consumer(it) } else consumer(it)
}.onFailure { logger.catching(it) }
}.catch { logger.catching(it) }
.launchIn(scope)
.launchIn(kordRef)

/**
* @suppress
Expand Down Expand Up @@ -515,7 +515,7 @@ public open class ExtensibleBot(
*/
@Throws(EventHandlerRegistrationException::class)
public inline fun <reified T : Event> registerListenerForHandler(handler: EventHandler<T>): Job {
return on<T> {
return on<T>(scope = handler.coroutineScope) {
handler.call(this)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import com.kotlindiscord.kord.extensions.utils.getKoin
import dev.kord.core.Kord
import dev.kord.core.event.Event
import io.github.oshai.kotlinlogging.KotlinLogging
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import org.koin.core.component.inject
import java.util.*
Expand Down Expand Up @@ -73,6 +74,13 @@ public open class EventHandler<T : Event>(
/** Cached locale variable, stored and retrieved by [getLocale]. **/
public var resolvedLocale: Locale? = null

/**
* Coroutine scope used to launch this event handler when handling a new event.
*
* Defaults to the current [Kord] instance.
*/
public var coroutineScope: CoroutineScope = kord

/**
* An internal function used to ensure that all of an event handler's required arguments are present.
*
Expand Down

0 comments on commit 4575003

Please sign in to comment.