Comments (6)
Hi!
If we take the problem the other way around, wouldn't it be more surprising that the signal didn't subscribe eagerly, ie probably missing some values emited by the observable ? This wasn't an issue with the signals because you always get the latest value when reading them.
Also can you give us more insight, what are the consequences for you that model.errors$
is subscribed eargerly ?
Edit: For the sake of completeness, this specific behavior can be implemented in userland. This has already been done by the ngxtension library with toLazySignal
.
from angular.
Hello!
It depends on the point of view. In the signal world, basically everything is lazy-evaluated, so I wouldn't mind if the subscription doesn't happen immediately. We could catch any "missing" value with a piped shareReplay({ bufferCount: 1, refCount: true })
if I understand it correctly (just a quick thought).
The error$
observable is just an example, but the consequence is processing time. For example, it can be even worse if async validation is used which can be arbitrarily complex. And if the observable emits immediately on subscription (which can be true for Observables created from BehaviourSubjects, ReplaySubjects, etc.), it might start network calls, for example.
Additionally, Observables are cold/lazy as well until there is at least one active subscriber. And for me, creating a signal from an observable should not represent an active subscription until the signal itself is used somewhere.
Thanks for the link, we will take a look at it.
from angular.
I think toSignal
is actually what you want here.
It's intended to be used like the async
pipe - converting to signals at the point where the data is used inside of a component. This ensures that the subscription is managed correctly and cleaned up when the data from the Observable
is no longer in use (unlike toLazySignal
which leaks subscriptions).
That is, the toSignal
call itself is the trigger that the cold observable should be pulled, not the usage of the resulting signal in the template.
from angular.
@alxhub, toLazySignal()
doesn't leak subscriptions.
It is a wrapper around toSignal()
, and toSignal()
manages subscriptions using an injector that is passed to toSignal()
.
So when a component is destroyed, subscriptions will be terminated by the underlying toSignal()
(if manualCleanup
is not set - all the options are transferred to toSignal()
).
toLazySignal()
asserts that it runs in an injection context.
You can see and try it here:
https://stackblitz.com/edit/stackblitz-starters-cysf3d?devToolsHeight=75&file=src%2Fmain.ts
from angular.
Yeah, I should be more clear. toLazySignal
itself doesn't truly "leak" subscriptions, but it's easy to end up in a situation where you don't realize that it won't unsubscribe when you stop pulling the signal in your template. E.g. using toLazySignal
in a service, thinking that it'll maintain the same semantics as cold observables.
from angular.
I think
toSignal
is actually what you want here.It's intended to be used like the
async
pipe - converting to signals at the point where the data is used inside of a component. This ensures that the subscription is managed correctly and cleaned up when the data from theObservable
is no longer in use (unliketoLazySignal
which leaks subscriptions).That is, the
toSignal
call itself is the trigger that the cold observable should be pulled, not the usage of the resulting signal in the template.
These are valid points, however the async
pipe is kind of lazy as well. In this example the observable is not subscribed until the async
pipe is created, and unsubscribed when the pipe is destroyed.
We could create the signal from the observable when we actually need it (similarly how the async
pipe is created on the fly), but there are other design choices (e.g. immutability, DI, etc.) that could prevent this. And just by looking at the definition / usage of the signals, one could expect that the signals should be just created at construction time (by toSignal
, input
, signal
, computed
or by any other means) and used when needed.
Back to the original example:
Imagine that we have these pages that can produce error messages. These error messages are constructed from validation errors by an observable (through rxjs
mapping, for example). The component that displays the errors of the current page is only interested in the error messages produced by the active page. Additionally, there could be use-cases when we don't want to subscribe to the validation error messages at all.
With signals, this can be easily implemented, because (from the docs): "Computed signals are both lazily evaluated and memoized"
readonly validationResults: Signal<...>;
readonly validationErrors = computed(() => createErrorMessages(this.validationResults()));
readonly isErrorsNeeded = signal(false);
readonly errors = computed(() => {
if (!this.isErrorsNeeded()) {
return [];
}
return this.validationErrors();
});
The errors
itself is only read for the active page and the validationErrors
is only read if the current value of isErrorsNeeded
is true
.
However, since the validationErrors
comes from a library as an Observable<string[]>
, it would be nice if we could just drop-in-replace the computed signal with toSignal(validationErrors$)
. And since we cannot (and shouldn't) create signals in computed signals, there is no way to easily integrate rxjs-based libraries into lazy-evaluated signal-based components.
from angular.
Related Issues (20)
- NgZoneSchedulingMode not exported HOT 1
- Page Not Found HOT 1
- Functions are missing from localForage after updating Angular to latest version HOT 2
- "updateOn: 'blur'" does not work in formBuilder/formControl HOT 11
- App-shell docs are out-of-date
- https://angular.dev/guide/security not found HOT 2
- Destroy component itself HOT 5
- Image lazy loading doesn't work in SSR when using ngTemplateOutlet and disabled hydration
- @angular/compiler `parseTemplate` fn does not properly parse `HTML` string element text content containing `@` HOT 2
- Angular 17 SSR: Slow server response time when using wildcard route HOT 5
- ERROR LOADING PAGES AFTER USE router.navigate
- SSR fails when root AppComponent in index.html is self-closing HOT 1
- foo = signal(''): if string is empty, !!foo () returns false HOT 1
- Form input mask provided by the framework HOT 6
- [Feature] Introduce Type-safe Token Providing HOT 7
- docs: `inject()` is missing all overloads HOT 2
- Add distinction between model() and model.required() on type level HOT 1
- Standalone Component Exports HOT 1
- Set ViewEncapsulation per module HOT 2
- setting signal outside of angular zone error HOT 3
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from angular.