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

com.github.thorbenkuck.network.connection.EventHandler Maven / Gradle / Ivy

The newest version!
package com.github.thorbenkuck.network.connection;

import java.util.ArrayList;
import java.util.List;
import java.util.function.Consumer;

public class EventHandler {

    private final List> consumers = new ArrayList<>();

    public void addHandler(Consumer consumer) {
        consumers.add(consumer);
    }

    public void addHandler(Runnable runnable) {
        consumers.add(new RunnableWrapper<>(runnable));
    }

    public void removeHandler(Consumer consumer) {
        consumers.remove(consumer);
    }

    @SuppressWarnings("SuspiciousMethodCalls")
    public void removeHandler(Runnable consumer) {
        consumers.remove(new RunnableWrapper<>(consumer));
    }

    public void propagate(T t) {
        ArrayList> copy = new ArrayList<>(this.consumers);
        copy.forEach(c -> c.accept(t));
    }

    private static class RunnableWrapper implements Consumer {

        private final Runnable root;

        private RunnableWrapper(Runnable root) {
            this.root = root;
        }

        @Override
        public void accept(T t) {
            root.run();
        }

        @Override
        public boolean equals(Object o) {
            return root.equals(o);
        }

        @Override
        public String toString() {
            return root.toString();
        }

        @Override
        public int hashCode() {
            return root.hashCode();
        }
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy