Interface Signal<T>

Type Parameters:
T - the type of data propagated with this signal
All Superinterfaces:
Consumer<T>, Observer<T>, Sensor

public interface Signal<T> extends Consumer<T>, Observer<T>

A signal, notifying its listeners and consumers each time it occurs, carrying data. For an event without data, see Event.

A signal is triggered with accept(Object), notifying its listeners and consumers in the order they were added, the consumers receiving the data.

Signals provide access to their Observer via observer(), which can be used to add listeners and consumers, but can not be used to trigger the signal.

Unhandled exceptions occurring in a listener or consumer will prevent further ones from being notified.

Thread Safety: Listener and consumer management (add/remove) is thread-safe. However, triggering via accept(Object) is NOT thread-safe and should be performed from a single thread (such as an application UI thread).

Signal<Boolean> signal = Signal.signal();

signal.addListener(this::doSomething);

signal.addConsumer(this::onBoolean);

signal.accept(true);

Observer<Boolean> observer = signal.observer();

observer.addConsumer(this::onBooleanElsewhere);

Listeners and consumers can be added using a WeakReference, so they must be strongly referenced elsewhere, a lambda or method reference only referenced by the observer being garbage collected right away.

// listener and consumer are fields
observer.addWeakListener(listener);
observer.addWeakConsumer(consumer);

Any weak references that no longer refer to a listener or consumer instance are cleared when listeners or consumers are added or removed.

A factory for Signal instances via signal().

See Also:
  • Method Details

    • accept

      void accept(@Nullable T data)
      Triggers this signal, notifying its listeners, and its consumers with the given data.
      Specified by:
      accept in interface Consumer<T>
      Parameters:
      data - data associated with the signal
    • observer

      Observer<T> observer()
      Description copied from interface: Observer
      Returns the underlying Observer to which listener and consumer operations are delegated.

      For AbstractObserver subclasses this method returns this. For wrapper types, this returns the delegate observer.

      Specified by:
      observer in interface Observer<T>
      Returns:
      an observer notified each time this signal occurs, which can not trigger it
    • signal

      static <T> Signal<T> signal()
      Creates a new Signal.
      Type Parameters:
      T - the type of data propagated with the signal
      Returns:
      a new Signal