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

org.rx.core.EventPublisher Maven / Gradle / Ivy

There is a newer version: 3.0.0
Show newest version
package org.rx.core;

import lombok.*;
import org.rx.bean.FlagsEnum;
import org.rx.bean.NEnum;
import org.rx.util.function.TripleAction;

import java.util.EventListener;
import java.util.concurrent.CompletableFuture;

import static org.rx.core.Constants.NON_UNCHECKED;

public interface EventPublisher> extends EventListener {
    @NoArgsConstructor(access = AccessLevel.PRIVATE)
    class StaticEventPublisher implements EventPublisher {
    }

    @RequiredArgsConstructor
    enum EventFlags implements NEnum {
        NONE(0),
        DYNAMIC_ATTACH(1),
        QUIETLY(1 << 1);

        @Getter
        final int value;
    }

//    StaticEventPublisher STATIC_EVENT_INSTANCE = new StaticEventPublisher();
    StaticEventPublisher STATIC_QUIETLY_EVENT_INSTANCE = new StaticEventPublisher() {
        @Override
        public FlagsEnum eventFlags() {
            return Constants.EVENT_ALL_FLAG;
        }
    };

    default FlagsEnum eventFlags() {
        return Constants.EVENT_DYNAMIC_FLAG;
    }

    @NonNull
    default ThreadPool asyncScheduler() {
        return Tasks.nextPool();
    }

    default  void attachEvent(String eventName, TripleAction eventDelegate) {
        attachEvent(eventName, eventDelegate, true);
    }

    default  void attachEvent(@NonNull String eventName, TripleAction eventDelegate, boolean combine) {
        Delegate d = Delegate.wrap(this, eventName);
        if (combine) {
            d.combine(eventDelegate);
            return;
        }
        d.replace(eventDelegate);
    }

    default  void detachEvent(@NonNull String eventName, TripleAction eventDelegate) {
        Delegate d = Delegate.wrap(this, eventName);
        d.remove(eventDelegate);
    }

    @SuppressWarnings(NON_UNCHECKED)
    @SneakyThrows
    default  void raiseEvent(@NonNull String eventName, TEvent event) {
        Delegate d = Delegate.wrap(this, eventName);
        d.invoke((TSender) this, event);
    }

    @SuppressWarnings(NON_UNCHECKED)
    @SneakyThrows
    default  void raiseEvent(Delegate eventDelegate, @NonNull TEvent event) {
        if (eventDelegate.isEmpty()) {
            return;
        }
        eventDelegate.invoke((TSender) this, event);
    }

    default  CompletableFuture raiseEventAsync(String eventName, TEvent event) {
        return asyncScheduler().runAsync(() -> raiseEvent(eventName, event));
    }

    default  CompletableFuture raiseEventAsync(Delegate eventDelegate, TEvent event) {
        if (eventDelegate.isEmpty()) {
            return CompletableFuture.completedFuture(null);
        }
        return asyncScheduler().runAsync(() -> raiseEvent(eventDelegate, event));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy