hilla icon indicating copy to clipboard operation
hilla copied to clipboard

Add support for computed full-stack signals

Open peholmst opened this issue 11 months ago • 2 comments

Describe your motivation

When working with signals to build a more complex UI, you often want to compute one signal from another. The resulting computed signal is then a read-only signal whose value changes whenever the original signal value changes. This already exists on the client side through useComputed(). I would like something similar on the Java side.

Describe the solution you'd like

One to one

For mapping a signal to another, I'd like a map() method, similar to the one found in Stream and Optional:

ValueSignal<String> myValue = new ValueSignal<String>(null, String.class);
Signal<Boolean> hasMyValue = myValue.map(Objects::nonNull); // True whenever myValue contains a non-null value

The returned signal is read-only.

Many to one

For mapping multiple signals to one, I'd like something like this:

ValueSignal<String> name = new ValueSignal<String>("", String.class);
NumberSignal age = new NumberSignal(0d);
Signal<String> nameAndAge = computedSignal(() -> "%s (%d years)".formatted(name.getValue(), age.getValue()), name, age);

In this example, the computedSignal factory method takes two parameters: a Supplier that computes the value, and an array of signals that the computed signal depends on. Whenever any of the dependencies change, the computed signal is re-computed. If you can figure out a way of deducing the dependencies from the Supplier alone, it would be even better.

The returned signal is read-only.

Describe alternatives you've considered

No response

Additional context

No response

peholmst avatar Nov 27 '24 14:11 peholmst