Wolfizen icon

Custom MessageChannel Implementation [1/3]

Wolfizen | PRO | 01/12/16 01:48:13 AM UTC | 0 ⭐ | 272 👁️ | Never ⏰ | []
Java |

2.5 KB

|

None

|

0 👍

/

0 👎

import javax.annotation.Nullable;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Stream;
 
/**
 * Custom implementation of {@link org.spongepowered.api.text.channel.MessageChannel MessageChannel}
 *
 * @param <R> The targeted type to receive messages
 * @param <M> The type of message to be sent to recipients
 */
public interface MessageChannel<R,M> {
 
    /**
     * Sends a message to all recipients.
     *
     * @param message The message to be sent
     *
     * @implSpec The default implementation is to chain {@code send(null, message)}
     */
    default void send(M message) {
        send(null, message);
    }
 
    /**
     * Sends a message to all recipients.
     *
     * @param sender The object which is sending the message
     * @param message The message to be sent
     *
     * @see MessageChannel#transformMessage(Object, R, M)
     */
    default void send(@Nullable Object sender, M message) {
        Objects.requireNonNull(message, "message cannot be null");
        getRecipients().forEach(recipient -> {
            transformMessage(sender, recipient, message).ifPresent(transformedMessage -> sendTo(recipient, transformedMessage));
        });
    }
 
    /**
     * Transforms a message with respect to a recipient.
     * <p>
     *     {@code Optional.empty()} will be returned if the transformation decides this recipient should not receive the message
     * </p>
     *
     * @param sender The object which is sending the message
     * @param recipient The individual recipient who will be receiving the message
     * @param originalMessage The message to be transformed
     *
     * @return The transformed message
     */
    default Optional<M> transformMessage(@Nullable Object sender, R recipient, M originalMessage) {
        return Optional.of(originalMessage);
    }
 
    /**
     * Obtains a {@code Stream} of the channel recipients.
     * <p>
     *     The recipients may change, so it is recommended to consume this Stream immediately.
     * </p>
     *
     * @return The current list of recipients
     */
    Stream<R> getRecipients();
 
    /**
     * Sends an arbitrary message to an arbitrary recipient.
     * <p>
     *     Mostly an implementation detail, as internally describes how to send a message to a recipient.
     * </p>
     *
     * @param recipient The recipient to send the message to
     * @param message The message to be sent
     */
    void sendTo(R recipient, M message);
}

Comments