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();

    default FlagsEnum eventFlags() {
        return EventFlags.DYNAMIC_ATTACH.flags();
    }

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

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

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

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

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

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

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

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




© 2015 - 2024 Weber Informatics LLC | Privacy Policy