All Downloads are FREE. Search and download functionalities are using the official Maven repository.

dev.robocode.tankroyale.botapi.internal.EventHandler Maven / Gradle / Ivy

The newest version!
package dev.robocode.tankroyale.botapi.internal;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Consumer;

/**
 * Event handler which processes events in the order they have been added to the handler.
 */
final class EventHandler {
    private final List subscriberEntries = new CopyOnWriteArrayList<>();

    void subscribe(Consumer subscriber, int priority) {
        subscriberEntries.add(new EntryWithPriority(subscriber, priority));
    }

    void subscribe(Consumer subscriber) {
        subscribe(subscriber, 1);
    }

    void publish(T event) {
        subscriberEntries.sort(new EntryWithPriorityComparator());
        for (EntryWithPriority entry : new ArrayList<>(subscriberEntries)) {
            entry.subscriber.accept(event);
        }
    }

    class EntryWithPriority {
        private final int priority; // Lower values means lower priority
        private final Consumer subscriber;

        EntryWithPriority(Consumer subscriber, int priority) {
            this.subscriber = subscriber;
            this.priority = priority;
        }
    }

    class EntryWithPriorityComparator implements Comparator {
        @Override
        public int compare(EntryWithPriority e1, EntryWithPriority e2) {
            return e2.priority - e1.priority;
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy