Skip to content

Commit 4f70ab9

Browse files
committed
Remove the listener the JDA command handler added on bean destroyal
1 parent 335ce0d commit 4f70ab9

File tree

2 files changed

+35
-1
lines changed

2 files changed

+35
-1
lines changed

src/main/java/net/kautler/command/handler/CommandHandlerJda.java

Lines changed: 17 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434
import org.apache.logging.log4j.Logger;
3535

3636
import javax.annotation.PostConstruct;
37+
import javax.annotation.PreDestroy;
3738
import javax.enterprise.context.ApplicationScoped;
3839
import javax.enterprise.event.Event;
3940
import javax.enterprise.inject.Instance;
@@ -137,7 +138,7 @@ private void setCustomPrefixProvider(Instance<PrefixProvider<? super Message>> c
137138
}
138139

139140
/**
140-
* Adds this command handler to the injected {@code DiscordApi} instances as message create listener.
141+
* Adds this command handler to the injected {@code JDA} and {@code ShardManager} instances as event listener.
141142
*/
142143
@PostConstruct
143144
private void addListener() {
@@ -173,6 +174,21 @@ private void addListener() {
173174
}
174175
}
175176

177+
/**
178+
* Removes this command handler from the injected {@code JDA} and {@code ShardManager} instances as event listener.
179+
*/
180+
@PreDestroy
181+
private void removeListener() {
182+
Stream.concat(
183+
jdas.stream(),
184+
jdaCollections.stream().flatMap(Collection::stream)
185+
).forEach(jda -> jda.removeEventListener(this));
186+
Stream.concat(
187+
shardManagers.stream(),
188+
shardManagerCollections.stream().flatMap(Collection::stream)
189+
).forEach(shardManager -> shardManager.removeEventListener(this));
190+
}
191+
176192
@Override
177193
public void onEvent(GenericEvent event) {
178194
if (event instanceof MessageReceivedEvent) {

src/test/groovy/net/kautler/command/handler/CommandHandlerJdaTest.groovy

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -373,6 +373,24 @@ class CommandHandlerJdaTest extends Specification {
373373
}
374374
}
375375

376+
@Use(ContextualInstanceCategory)
377+
def 'shutting down the container should remove the listeners'() {
378+
when:
379+
weld.shutdown()
380+
381+
then:
382+
[
383+
jda,
384+
jdaInCollection1,
385+
jdaInCollection2,
386+
shardManager,
387+
shardManagerInCollection1,
388+
shardManagerInCollection2
389+
].each {
390+
1 * it.removeEventListener(commandHandlerJda.ci())
391+
}
392+
}
393+
376394
@ApplicationScoped
377395
static class TestEventReceiver {
378396
@Inject

0 commit comments

Comments
 (0)