From 9705915e21b243f266b261629dc8902a14ea51f9 Mon Sep 17 00:00:00 2001 From: TheMode Date: Tue, 8 Jun 2021 14:07:27 +0200 Subject: [PATCH] Add support for predicate expiration --- .../minestom/server/event/EventListener.java | 21 +++++++++++-------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/src/main/java/net/minestom/server/event/EventListener.java b/src/main/java/net/minestom/server/event/EventListener.java index 93497f279..6bc1a9fe4 100644 --- a/src/main/java/net/minestom/server/event/EventListener.java +++ b/src/main/java/net/minestom/server/event/EventListener.java @@ -1,6 +1,5 @@ package net.minestom.server.event; -import net.minestom.server.utils.time.UpdateOption; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; @@ -39,8 +38,8 @@ public interface EventListener { private final Class eventType; private final List> filters = new ArrayList<>(); - private int expirationCount; - private UpdateOption expirationTime; + private int expireCount; + private Predicate expireWhen; private Consumer handler; protected Builder(Class eventType) { @@ -52,13 +51,13 @@ public interface EventListener { return this; } - public EventListener.Builder expirationCount(int expirationCount) { - this.expirationCount = expirationCount; + public EventListener.Builder expireCount(int expireCount) { + this.expireCount = expireCount; return this; } - public EventListener.Builder expirationTime(UpdateOption expirationTime) { - this.expirationTime = expirationTime; + public EventListener.Builder expireWhen(Predicate expireWhen) { + this.expireWhen = expireWhen; return this; } @@ -68,7 +67,7 @@ public interface EventListener { } public @NotNull EventListener build() { - AtomicInteger expirationCount = new AtomicInteger(this.expirationCount); + AtomicInteger expirationCount = new AtomicInteger(this.expireCount); final boolean hasExpirationCount = expirationCount.get() > 0; final var filters = new ArrayList<>(this.filters); @@ -81,6 +80,10 @@ public interface EventListener { @Override public @NotNull Result run(@NotNull T event) { + // Expiration predicate + if (expireWhen != null && expireWhen.test(event)) { + return Result.EXPIRED; + } // Filtering if (!filters.isEmpty()) { if (filters.stream().anyMatch(filter -> !filter.test(event))) { @@ -92,7 +95,7 @@ public interface EventListener { if (handler != null) { handler.accept(event); } - // Expiration check + // Expiration count if (hasExpirationCount && expirationCount.decrementAndGet() == 0) { return Result.EXPIRED; }