When working in the world of rxjs, you have the ability to combine multiple Observables using the merge
operator. If you have an array of Observables, all you need to do is spread that array into the merge operator like this: merge(...arrayOfObservables)
. And if you're dealing with a 'higher-order' Observable (an Observable that emits other Observables), then you can utilize mergeAll
.
Now, I'm trying to achieve something similar to mergeAll
with Angular's new Signals. I have a Signal that contains an array of Signals,
all_the_states = signal([] as Signal<any>[])
. This Signal continuously gets updated over time using mutate
. My goal is to create a simple Signal called latest_state
that always holds the most recent value from any of the 'inner' Signals.
My initial thought was to go to "rxjs-land, merge, and return", which led me to try the following approach:
latest_state = toSignal(
merge(...this.all_the_states().map((single) => toObservable(single))),
{ initialValue: null }
)
However, whenever I add something to all_the_states
, latest_state
remains null.
Another attempt involved the following code snippet:
higher_order_observable: Observable<Observable<any>[]> =
toObservable(this.selection_streams).pipe(
map(signals => signals.map(signal => toObservable(signal)))
)
single_observable: Observable<any> =
this.higher_order_observable.pipe(mergeAll(), mergeAll())
latest_state = toSignal(this.single_observable, { initialValue: null })
This solution seems promising in terms of types, although I am uncertain about the double mergeAll
. However, Angular throws an error at me saying
NG0203: toObservable() can only be used within an injection context such as a constructor, a factory function, a field initializer, or a function used with 'runInInjectionContext'
even before reaching the double mergeAll
.