Skip to content

Commit

Permalink
Make manage cancel tasks more consistently
Browse files Browse the repository at this point in the history
  • Loading branch information
FluxCapacitor2 committed Sep 15, 2024
1 parent 25f7960 commit bff7e65
Showing 1 changed file with 15 additions and 4 deletions.
19 changes: 15 additions & 4 deletions common/src/main/kotlin/com/bluedragonmc/server/utils/TaskUtils.kt
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package com.bluedragonmc.server.utils

import com.bluedragonmc.server.Game
import com.bluedragonmc.server.event.GameEvent
import com.bluedragonmc.server.event.GameStateChangedEvent
import com.bluedragonmc.server.module.GameModule
import com.bluedragonmc.server.module.minigame.WinModule
import net.minestom.server.event.Event
Expand All @@ -20,19 +22,28 @@ fun <T : Event> Task.cancelOn(game: Game, eventType: Class<out T>, condition: Pr
eventNode.addListener(eventType) { event ->
if (condition.test(event)) {
logger.debug("Canceling task with id ${this@cancelOn.id()} because event of type ${eventType.simpleName} was triggered.")
this@cancelOn.cancel()
game.unregister(module)
game.unregister(module) // `unregister` triggers `deinitialize`, which cancels the task
}
}
}

override fun deinitialize() {
this@cancelOn.cancel()
}
}
game.register(module) { true }
game.modules.add(module)
return this
}

/**
* Cancels the task when a [WinModule.WinnerDeclaredEvent] is received.
* Cancels the task when the game state is set to ENDING, a winner is declared, or game modules are uninitialized, whichever comes first.
* @return The task, for method chaining
*/
fun Task.manage(game: Game): Task = cancelOn(game, WinModule.WinnerDeclaredEvent::class.java)
fun Task.manage(game: Game): Task = cancelOn(game, GameEvent::class.java) { event ->
when (event) {
is GameStateChangedEvent -> event.newState == GameState.ENDING
is WinModule.WinnerDeclaredEvent -> true
else -> !Game.games.contains(game)
}
}

0 comments on commit bff7e65

Please sign in to comment.