We should remove the `onDestroy` listener once subscription is unsubscribed because components might not be destroyed yet, but they still would capture subscribers.
PR Close#61882
Since `DestroyRef.onDestroy` throws if the `DestroyRef` is already
destroyed, there is a need to be able to tell if it is already destroyed
before attempting to register a callback.
PR Close#61849
Adds fix directly for `takeUntilDestroyed` to unsubscribe when already
destroyed instead of putting
synchronous behavior on `DestroyRef.onDestroyed` callback as in #58008fixes#54527
PR Close#61847
The observable terminates immediately when `error` is called, and no further emissions or completion notifications occur. Thus, we have to remove the listener in both the `error` and `complete` notifications.
PR Close#61596
`Resource.error` used to return `unknown`. Now it's `Error | undefined`.
For non-`Error` types they are encapsulated with the `Error` type.
PR Close#61441
The observable terminates immediately when `error` is called, and no further emissions or completion notifications occur. Thus, we have to remove the `abort` listener in both the `error` and `complete` notifications.
PR Close#58306
In other parts of the code, calls to the `assertInInjectionContext` function are guarded with `ngDevMode`. This change aligns these parts of the code with other implementations that drop such assertions in production.
PR Close#61564
In other parts of the code, calls to the `assertInInjectionContext` function are guarded with `ngDevMode`. This change aligns these parts of the code with other implementations that drop such assertions in production.
PR Close#61560
As decided in the Resource RFC, this commit renames `loader` in `rxResource`
to `stream`. Some logic is left in to support gradual rollout of this change
in g3.
PR Close#60919
With the changes in #59573, `resource` can now define a `stream` rather than a `loader`.
In the same PR, `rxResource` was updated to leverage this new functionality to handle multiple responses from the underlying observable,
rather than just the first one as it was previously.
This commit renames the `loader` option of `rxResource` into `stream` to be better aligned with its new behavior.
The previous version is temporarily kept and marked as deprecated to help migrating the current usage.
Before
```
usersResource = rxResource({
request: () => ...,
loader: ({ request }) => ...
});
```
After
```
usersResource = rxResource({
request: () => ...,
stream: ({ request }) => ...
});
```
PR Close#59910
This commit adds a flag `forceSyncFirstEmit` which opts in to the pending
new behavior for `toObservable`, which emits the first value synchronously.
This flag is only really meant for use during a short migration period
while we update g3, and is not meant for prolonged usage. As a result, it's
marked deprecated.
PR Close#60640
This commit removes the previously added `rejectErrors` option from
`toSignal` which was meant to create similar behavior to what happens
with unhandled errors in `AsyncPipe`.
This option promotes unhandled exceptions and attaches behaviors that we
do not believe are desirable as an option offered by the framework:
* Unhandled errors that are thrown lose the context of where the error
ocurred. Throwing the error where the signal is read allows error
handling to be performed at the signal's usage location
* With this feature, the value of the signal remains set to the initial
value or the previous successful value coming out of the `Observable`.
We do not feel this is appropriate implicit behavior but should be an
explicit choice by the application. Signals are built to represent
state. When an observable stream is converted to a stateful
representation, there should be a choice made about what state should
be presented when an error occurs
* If an error occurs but the signal value is never read in its error
state, this is not an application state error that should result in an
unhandled exception.
* While Angular does not have error boundaries today, there is likely to
be investigation in the near future to address increased risk of
errors thrown from signals such as this in templates. Without
pre-designing any specifics, it is possible that this type of feature
would require the error to be thrown from the signal. We are subsequently
not prepared to commit to stabilizing the `toSignal` API with the
`rejectErrors` option and its current behavior.
Developers that desire similar behavior to `rejectErrors` have several
options, the simplest of which would be something similar to
`toSignal(myStream.pipe(catchError(() => EMPTY)))`.
PR Close#60397
The refactoring of `resource()` to use `linkedSignal()` introduced the
potential for a race condition where resources would get stuck and not update
in response to a request change. This occurred under a specific condition:
1. The request changes while the resource is still in loading state
2. The resource resolves the previous load before its `effect()` reacts to the
request change.
In practice, the window for this race is small, because the request change in
(1) will schedule the effect in (2) immediately. However, it's easier to
trigger this sequencing in tests, especially when one resource depends on the
output of another.
To fix the race condition, the resource impl is refactored to track the request
in its state, and ignore resolved values or streams for stale requests. This
refactoring actually makes the resource code simpler and easier to follow as
well.
Fixes#59842
PR Close#59851
Before `resource()` resolves, its value is in an unknown state. By default
it returns `undefined` in these scenarios, so the type of `.value()`
includes `undefined`.
This commit adds a `defaultValue` option to `resource()` and `rxResource()`
which overrides this default. When provided, an unresolved resource will
return this value instead of `undefined`, which simplifies the typing of
`.value()`.
PR Close#59655
This commit adds support for creating `resource()`s with streaming response
data. A streaming resource is defined by a `stream` option instead of a
`loader`, with `stream` being a function returning
`Promise<Signal<{value: T}|{error: unknown}>>`. Once the streaming loader
resolves to a `Signal`, it can continue to update that signal over time, and
the values (or errors) will be delivered to via the resource's state.
`rxResource()` is updated to leverage this new functionality to handle
multiple responses from the underlying Observable.
PR Close#59573
Originally the `T` in `Resource<T>` represented the resolved type of the
resource, and `undefined` was explicitly added to this type in the `.value`
signal. This turned out to be problematic, as it wasn't possible to write a
type for a resource which didn't return `undefined` values. Such a type is
useful for 2 reasons:
1. to support narrowing of the resource type when `Resource.hasValue()`
returns `true`.
2. for resources which use a different value instead of `undefined` to
represent not having a value (for example, array resources which want to
use `[]` as their default).
Instead, this commit changes `resource()` and `rxResource()` to return an
explicit `ResourceRef<T|undefined>`, and removes the union with `undefined`
from all types related to the resource's value. This way, it's trivially
possible to write `Resource<T>` to represent resources where `.value` only
returns `T`.
`hasValue()` then actually works to perform narrowing, by narrowing the
resource type to `Exclude<T, undefined>`.
PR Close#59024
The `rxResource` was using `firstValueFrom` which isn't supported in rxjs 6.x. `@angular/core` currently supports rxjs 6 so we need this to be backwards compatible. This came up when trying to deploy the Material docs site which is still on rxjs 6 ([see](https://github.com/angular/components/actions/runs/11487971079/job/31973721563)).
PR Close#58341
This commit adds an operator to help rxjs observables important for rendering
keep the application unstable (and prevent serialization) until there is
an event (observable emits, completes, or errors, or the subscription is
unsubscribed). This helps with SSR for zoneless and also helps for when
operations are intentionally executed outside the Angular Zone but are
still important for SSR (i.e. angularfire and the zoneWrap helper hacks).
PR Close#56533
Implementations of two rxjs-interop APIs which produce `Resource`s from
RxJS Observables. `rxResource()` is a flavor of `resource()` which uses a
projection to an `Observable` as its loader (like `switchMap`).
PR Close#58255
The original effect design for Angular had one "bucket" of effects, which
are scheduled on the microtask queue. This approach got us pretty far, but
as developers have built more complex reactive systems, we've hit the
limitations of this design.
This commit changes the nature of effects significantly. In particular,
effects created in components have a completely new scheduling system, which
executes them as a part of the change detection cycle. This results in
behavior similar to that of nested effects in other reactive frameworks. The
scheduling behavior here uses the "mark for traversal" flag
(`HasChildViewsToRefresh`). This has really nice behavior:
* if the component is dirty already, effects run following preorder hooks
(ngOnInit, etc).
* if the component isn't dirty, it doesn't get change detected only because
of the dirty effect.
This is not a breaking change, since `effect()` is in developer preview (and
it remains so).
As a part of this redesigned `effect()` behavior, the `allowSignalWrites`
flag was removed. Effects no longer prohibit writing to signals at all. This
decision was taken in response to feedback / observations of usage patterns,
which showed the benefit of the restriction did not justify the DX cost.
The new effect timing is not yet enabled - a future PR will flip the flag.
PR Close#56501
The option introduced in 5df3e78c99 has been named `equals` whereas the existing option in `signal` is named `equal`.
This commit renames the new option to `equal` as well to keep the naming coherent across these APIs.
PR Close#56769
`toSignal` predates the decision to allow a more flexible equality check in
signals, and thus doesn't support a custom equality function. This commit
adds the ability to pass a custom value equality function. As a side effect,
it now adds the default equality check where it wasn't used before.
Fixes#55573
PR Close#56447
This commit introduces an addition to `output()` and
`outputFromObservable`()` —called `outputToObservable()`.
The helper lives in the RxJS interop package and allows agnostic
programmatic subscriptions to `OutputRef`s by converting the output
to an observable with `.pipe` etc.
The function is ideally used in all places where you subscribe to an
output programmatically. Those outputs in the future, with the new APIs,
may not be actual RxJS constructs, but abstract `OutputRef`'s that
simply expose a `.subscribe` method. The helper allows you to
agnostically convert outputs to RxJS observables that you can safely
interact with.
The observables are also completed automatically, if possible, when the
owning directive/component is destroyed— Something that is not
guaranteed right now.
PR Close#54650
Introduces a second API in addition to the new `output()` function.
The new function `outputFromObservable()` can be used to declare outputs
using the new `OutputRef` API and `output()` API, while using a custom
RxJS observable as data source.
This is something that is currently possible in Angular and we would
like to keep possible- even though we never intended to support custom
observables aside from RxJS-based `EventEmitter`.
The interop bridges the gap and allows you to continue using
`Subject`, `ReplaySubject`, `BehaivorSubjct,` - or cold custom
observables for outputs. You can still trigger logic only when
the output is subscribed- unlike with imperative `emit`s of
`EventEmitter` or the new `OutputEmitterRef`.
A notable difference is that you need two class members where you
previously could access the `Subject` directly. This is an intentional
trade-off we've made to ensure that all new outputs implement the
`OutputRef` interface and we are exposing a minimal API surface to
consumers of components that currently access the output
programmatically.
PR Close#54650
By default, `toSignal` transforms an `Observable` into a `Signal`, including
the error channel of the Observable. When an error is received, the signal
begins throwing the error.
`toSignal` is intended to serve the same purpose as the `async` pipe, but
the async pipe has a different behavior with errors: it rejects them
outright, throwing them back into RxJS. Rx then propagates the error into
the browser's uncaught error handling logic. In the case of Angular, the
error is then caught by zone.js and reported via the application's
`ErrorHandler`.
This commit introduces a new option for `toSignal` called `rejectErrors`.
With that flag set, `toSignal` copies the async pipe's behavior, allowing
for easier migrations.
Fixes#51949
PR Close#52474
This commit cleans up the signatures of `toSignal` to better handle the
types of situations that it might be used in, and produce better type
inference results.
Fixes#50687Fixes#50591
Co-authored-by: Andrew Scott <atscott@google.com>
PR Close#51991
Revert (with improvements of): dcf18dc74c
We recently landed a change that allows `toSignal` to be called
from within reactive contexts (e.g. `effect`/`computed`). After
more thorough investigatio and consideration with the team, we
feel like allowing `toSignal` to be called in such contexts is
encouraging non-ideal / hard-to-notice code patterns.
e.g. a new subscription to an observable is made every time `toSignal`
is invoked. There is no caching done here. Additionally, multiple new
subscriptions can trigger unintended side-effects- that may slow down
the app, result in incorrect/unexpected behavior or perform unnecessary
work.
Users should instead move the `toSignal` call outside of the `computed`
or `effect` and then read the signal values from within their `computed`. e.g.
```ts
computed(() => {
const smth = toSignal(coldObservable$)
return smth() + 2;
}
```
--> should instead be:
```ts
const smth = toSignal(coldObsverable$);
computed(() => smth() + 2);
```
In cases where a new subscription for each invocation is actually intended, a manual
subscription can be made. That way it's also much more obvious to users
that they are triggering side-effects every time, or causing new
subscriptions.
PR Close#52049