org.rx.core.EventPublisher Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of rxlib Show documentation
Show all versions of rxlib Show documentation
A set of utilities for Java
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));
}
}