diff --git a/src/main/java/me/libraryaddict/disguise/utilities/packets/LibsPackets.java b/src/main/java/me/libraryaddict/disguise/utilities/packets/LibsPackets.java index ec043366..108ec6b7 100644 --- a/src/main/java/me/libraryaddict/disguise/utilities/packets/LibsPackets.java +++ b/src/main/java/me/libraryaddict/disguise/utilities/packets/LibsPackets.java @@ -9,10 +9,7 @@ import org.bukkit.Bukkit; import org.bukkit.entity.Player; import java.lang.reflect.InvocationTargetException; -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.Map; +import java.util.*; /** * Created by libraryaddict on 3/01/2019. @@ -72,22 +69,31 @@ public class LibsPackets { } public void sendDelayed(final Player observer) { - for (final Map.Entry> entry : delayedPackets.entrySet()) { - Bukkit.getScheduler().scheduleSyncDelayedTask(LibsDisguises.getInstance(), new Runnable() { - public void run() { - try { - for (PacketContainer packet : entry.getValue()) { - ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false); - } - } - catch (InvocationTargetException e) { - e.printStackTrace(); - } + Iterator>> itel = delayedPackets.entrySet().iterator(); + Optional largestTick = delayedPackets.keySet().stream().max(Integer::compare); - if (isSpawnPacket) { - PacketsManager.getPacketsHandler().removeCancel(disguise, observer); + if (!largestTick.isPresent()) { + return; + } + + while (itel.hasNext()) { + Map.Entry> entry = itel.next(); + // If this is the last delayed packet + final boolean isRemoveCancel = isSpawnPacket && largestTick.get().equals(entry.getKey()); + + Bukkit.getScheduler().scheduleSyncDelayedTask(LibsDisguises.getInstance(), () -> { + try { + for (PacketContainer packet : entry.getValue()) { + ProtocolLibrary.getProtocolManager().sendServerPacket(observer, packet, false); } } + catch (InvocationTargetException e) { + e.printStackTrace(); + } + + if (isRemoveCancel) { + PacketsManager.getPacketsHandler().removeCancel(disguise, observer); + } }, entry.getKey()); } }