Skip to content

Event as Coroutines Flow

Gabriel Souza edited this page Jul 18, 2020 · 2 revisions

Event Flow is a reactive way to listen to events, its use Coroutines Flow.

inline fun <reified T : Event> Plugin.eventFlow(
    assign: Player? = null,
    priority: EventPriority = EventPriority.NORMAL,
    ignoreCancelled: Boolean = false
    ...
): Flow<T>

also extension for WithPlugin.

A simple example is for retrieve a player chat input on a command or menu interaction.

command("yourName") {
  executorPlayer {
    sender.msg("please type your name at the chat")

    val input = plugin.eventFlow<AsyncPlayerChatEvent>(
        assign = sender,
        priority = EventPriority.LOWEST,
        ignoreCancelled = true
    ).filter { it.player.name == sender.name }
    .map { it.player.name }
    .first()
    
    sender.msg("your name is: $input")
    
    doSomethingItTheName(input)
  }
}

The optional assign: Is used for when you need to hold an event flow ONLY when the player is connected, if the player disconnect, will cancel the Flow, avoiding leaks.

You could use it with withTimeoutOrNull() {} from Coroutines as well to make more safe your flows.

command("yourName") {
  executorPlayer {
    sender.msg("please type your name at the chat")

    val input = withTimeoutOrNull(20000) {
      plugin.eventFlow<AsyncPlayerChatEvent>(
          assign = sender,
          priority = EventPriority.LOWEST,
          ignoreCancelled = true
      ).filter { it.player.name == sender.name }
      .map { it.player.name }
      .first()
    } ?: fail("You took to long to input your name!")
    
    sender.msg("your name is: $input")
    
    doSomethingItTheName(input)
  }
}
Clone this wiki locally