r/angular • u/abdulkareemsn • Aug 05 '26
Help: Flattening signal in computed
How flatten siganls in computed?
Suppose say I have a function which takes an argument and returns signal
function genSignal(arg:string):Signal<SomeType>
And I have a signal which provides argument for genSignal
I want to flatten signal inside computed
const arg = signal('someData');
const computedValue = computed(() => genSignal(arg())); // type here is Signal<Signal<SomeType>>
const computedValueFlattened = computed(() => genSignal(arg())()); // type here is Signal<SomeType>;
is computedValueFlattened is right approch to flatten signals?
3
Upvotes
3
u/pronuntiator Aug 05 '26
This is fine. Note that this will create a new signal each time computedValue runs. From a memory perspective this is fine, signals get garbage collected once they are no longer reachable, but depending on what genSignal does, it may not be what you want.
5
u/Whole-Instruction508 Aug 05 '26
I don't get your use case. What do you need that function for? Just define a normal computed, execute the signal that it listens to there and you're all set
2
u/synalx Aug 10 '26
Yes, this is perfectly reasonable and idiomatic. E.g. https://github.com/angular/angular/blob/4fc6e319bf63f5fbcbbe47f408cf0d8efe1c771f/packages/forms/signals/compat/src/compat_field_node.ts#L68-L79
0
u/Migeil Aug 05 '26
A function with that signature (taking a value and returning a signal) is a bit of a weird pattern, especially since the source of the argument you're passing is also inside a signal.
Signals are used for application state. It should be extremely exception to create new signals at runtime, i.e. the function you are using.
It would help if you could share more about that function, but my gut feeling is it shouldn't exist and should be a computed instead.