Commit graph

30 commits

Author SHA1 Message Date
Alex Rickabaugh
1ba9b7ac50 feat(core): resource composition via snapshots
* Define `ResourceSnapshot<T>` as a type union of possible states for a
`Resource<T>`.
* Add `Resource.snapshot()` to convert a `Resource` to a signal of its
  snapshot.
* Add `resourceFromSnapshots` to convert a reactive snapshot back into a
  `Resource`.

By converting resources from/to `Signal<ResourceSnapshot>`s, full
composition of resources is now possible on top of signal composition APIs
like `computed` and `linkedSignal`.

For example, a common feature request is to have a `Resource` which retains
its value when its reactive source (params) changes. This can now be built
as a utility, leveraging `linkedSignal`'s previous value capability:

```ts
function withPreviousValue<T>(input: Resource<T>): Resource<T> {
  const derived = linkedSignal({
    source: input.snapshot,
    computation: (snap, previous) => {
      if (snap.status === 'loading' && previous?.value) {
        // When the input resource enters loading state, we keep the value
        // from its previous state, if any.
        return {status: 'loading', value: previous.value.value};
      }

      // Otherwise we simply forward the state of the input resource.
      return snap;
    },
  });

  return resourceFromSnapshots(derived);
}

// In application code:

userId = input.required<number>();
user = withPreviousValue(httpResource(() => `/user/{this.userId()}`));
// if `userId()` switches, `user.value()` will keep the old value until
// the new one is ready!
```
2026-01-12 13:49:56 -08:00
Jessica Janiuk
e703433b4b Revert "feat(core): resource composition via snapshots"
This reverts commit 2a6fdda601.
2025-11-07 07:42:18 -08:00
Alex Rickabaugh
2a6fdda601 feat(core): resource composition via snapshots
* Define `ResourceSnapshot<T>` as a type union of possible states for a
`Resource<T>`.
* Add `Resource.snapshot()` to convert a `Resource` to a signal of its
  snapshot.
* Add `resourceFromSnapshots` to convert a reactive snapshot back into a
  `Resource`.

By converting resources from/to `Signal<ResourceSnapshot>`s, full
composition of resources is now possible on top of signal composition APIs
like `computed` and `linkedSignal`.

For example, a common feature request is to have a `Resource` which retains
its value when its reactive source (params) changes. This can now be built
as a utility, leveraging `linkedSignal`'s previous value capability:

```ts
function withPreviousValue<T>(input: Resource<T>): Resource<T> {
  const derived = linkedSignal({
    source: input.snapshot,
    computation: (snap, previous) => {
      if (snap.status === 'loading' && previous?.value) {
        // When the input resource enters loading state, we keep the value
        // from its previous state, if any.
        return {status: 'loading', value: previous.value.value};
      }

      // Otherwise we simply forward the state of the input resource.
      return snap;
    },
  });

  return resourceFromSnapshots(derived);
}

// In application code:

userId = input.required<number>();
user = withPreviousValue(httpResource(() => `/user/{this.userId()}`));
// if `userId()` switches, `user.value()` will keep the old value until
// the new one is ready!
```
2025-11-06 14:59:39 -08:00
JoostK
50d9d55f49 fix(core): fix narrowing of Resource.hasValue() (#63994)
This commit changes `Resource.hasValue()` and its derived types to improve narrowing
of resources whose generic type either does not include `undefined` (i.e. when a default
value has been provided) or when the generic type is `unknown`. This fixes the undesirable
behavior where `hasValue()` would cause the `else` branch of an `hasValue()` conditional
to have a narrowed type of `never`, given that the `hasValue()`'s type guard covers the
entire type range already (meaning that the type in the else-branch cannot be inhabited
in the type system, yielding the `never` type).

By making the `hasValue()` method only a type guard when the generic type includes `undefined`
these problems are avoided.

Fixes #60766
Fixes #63545
Fixes #63982

PR Close #63994
2025-09-23 14:20:55 +00:00
Matthieu Riegler
af33647145 refactor(core): remove usages of Promise.withResolvers (#63856)
Promise.withResolvers is Baseline 2024. Our policy is to support browsers in the scope of Basline widely available.

Fixes #63855

PR Close #63856
2025-09-17 15:21:51 +00:00
Joey Perrott
2fcafb65c5 build: rename defaults2.bzl to defaults.bzl (#63383)
Use defaults.bzl for the common macros

PR Close #63383
2025-08-25 15:45:01 -07:00
Joey Perrott
3df1dccebe refactor: various build and import specificer fixes for strict deps (#63323)
Change direct deps in bazel targets and import specifiers within files to maintain strict deps requirements ahead of enabling strict deps tests in the repo

PR Close #63323
2025-08-22 14:45:00 -07:00
Joey Perrott
cbc258eec8 build: remove ts_project_interop infrastructure (#62908)
Remove the interop macros and final usages

PR Close #62908
2025-07-31 09:12:58 +00:00
Joey Perrott
8bf97d1370 build: remove all usages of the interop_deps attr for ts_project and ng_project (#62732)
Remove all of the usages of interop_deps as attributes in the repo

PR Close #62732
2025-07-21 13:03:09 -04:00
Elizabeth
b8e415a717 fix(core): fix change tracking for Resource#hasValue (#62595)
When using `hasValue()` I would expect it to behave like any other
reactive value such that changes to the internal `value()` that do not
cause `hasValue()` to return anything different do not trigger change
detection, but this was not the case. This change wraps the value
checking in a `computed` such that it behaves as expected again while
still preserving the type narrowing.

PR Close #62595
2025-07-18 10:01:43 -04:00
Joey Perrott
b84859073b build: migrate to use web test runner rules (#62292)
Migrate karma tests throughout the repo to use the new web test runner based rule instead

PR Close #62292
2025-06-26 17:19:10 +00:00
Matthieu Riegler
36a193139a fix(core): allow to set a resource in an error state (#62253)
A resource is error state should still remain writable.

fixes #62241

PR Close #62253
2025-06-25 13:20:42 +00:00
Paul Gschwendtner
a137746110 build: migrate packages/core/test to new jasmine_test rule (#61902)
Migrates `packages/core/test` to the new `jasmine_test` rule. As part of
this, we are also removing an unnecessary/unused test fixture.

PR Close #61902
2025-06-12 10:00:09 +02:00
Joey Perrott
687e01865f build: migrate platform-server to rules_js (#61589)
Migrate platform-server to use ts_project and ng_project.

PR Close #61589
2025-05-22 11:35:55 -07:00
Maciej Sawicki
905194fa57 fix(core): reading resource value after reload in the error state (#61441)
When the resource is loading after reloading from the error state reading `Resource.value()` would return the default value instead of throwing an error.
This change prevents `Resource.hasValue()` from throwing an error in such a case.

PR Close #61441
2025-05-21 12:06:40 -07:00
Maciej Sawicki
b35396345c fix(core): getting resource value throws an error instead of returning undefined (#61441)
When there is an underlying error state it would not be possible to swallow the error with:
`computed(() => res.value()?.inner);`

PR Close #61441
2025-05-21 12:06:40 -07:00
Maciej Sawicki
05eb028c7a fix(core): narrow error type for resources API (#61441)
`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
2025-05-21 12:06:40 -07:00
Paul Gschwendtner
082cc5579d build: migrate all ng_module in packages/core/test (#61472)
Migrates all `ng_module` to `ng_project` in `packages/core/test/`.

PR Close #61472
2025-05-20 10:00:43 +00:00
Alex Rickabaugh
d0c9a6401a refactor(core): rename resource's request to params (#60919)
As decided in the resource RFC, this commit renames the `request` option of
a resource to `params`, including the subsequent argument passed to the
loader. It also corrects the type in the process to properly allow narrowing
of the `undefined` value.

Fixes #58871

PR Close #60919
2025-04-23 19:34:50 +00:00
Alex Rickabaugh
d8ca560a15 refactor(core): convert ResourceStatus to a string type (#60919)
An outcome of the Resource RFC was that we should use string constants for
communicating the resource status instead of an enum. This commit converts
`ResourceStatus` accordingly.

PR Close #60919
2025-04-23 19:34:50 +00:00
Pawel Kozlowski
0859a99e89 refactor(core): replace TestBed.flushEffects with tick (#60959)
Instead of stabilizing the TestBed.flushEffects() API we intend to
replace it with the tick() method (equivalent of ApplicationRef.tick().
The reasoning here is that we prefer tests running the entire
synchronization process (as in production apps) instead of invoking
parts of the synchronization process in a way that would naver happen
in a running application.

PR Close #60959
2025-04-23 09:54:30 +02:00
Andrew Kushnir
ae047c59c0 refactor(core): convert scripts within packages/core/test to relative imports (#60227)
This commit updates scripts within `packages/core/test` to relative imports as a prep work to the
upcoming infra updates.

PR Close #60227
2025-03-25 10:58:00 -07:00
Alex Rickabaugh
b592b1b051 fix(core): fix race condition in resource() (#59851)
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
2025-02-05 15:01:02 -08:00
Kristiyan Kostadinov
96e602ebe9 fix(core): cancel in-progress request when same value is assigned (#59280)
Fixes that `resource` wasn't cancelling its in-progress request if the same value as the current one is assigned.

Fixes #59272.

PR Close #59280
2025-01-29 08:40:11 -08:00
Alex Rickabaugh
127fc0dc84 fix(core): fix resource()'s previous.state (#59708)
When a resource first starts up, even if it transitions immediately to
`Loading` it should report a `previous.state` of `Idle`. It was reporting
`Loading` as the previous state in such a case because of an oversight in
the migration to `linkedSignal` which this commit addresses.

PR Close #59708
2025-01-28 09:40:29 +01:00
Alex Rickabaugh
168516462a feat(core): support default value in resource() (#59655)
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
2025-01-24 13:39:02 +01:00
Alex Rickabaugh
bc2ad7bfd3 feat(core): support streaming resources (#59573)
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
2025-01-21 09:55:32 -08:00
Alex Rickabaugh
01fffdb547 refactor(core): port resource() to linkedSignal() (#59024)
When the reactive `request` of a resource() notifies, it transitions to the
Loading state, fires the loader, and eventually transitions to Resolved.
With the prior implementation, a change of the `request` will queue the
effect, but the state remains unchanged until the effect actually runs. For
a brief period, the resource is in a state where the request has changed,
but the state has yet to update.

This is problematic if we want to use resources in certain contexts where we
care about the state of the resource in a synchronous way. For example, an
async validator backed by a resource might be checked after an update:

```
value.set(123);

if (validator.value()) {
  // value is still valid, even though the resource is dirty and will soon
  // flip to loading state (returning value(): undefined) while revalidating
}
```

To address this timing concern, `linkedSignal()` is used within the
`resource()` to synchronously transition the state in response to the
request changing. This ensures any followup reads see a consistent view of
the resource regardless of whether the effect has run.

This also addresses a race condition where `.set()` behaves differently on a
`resource()` depending on whether or not the effect has run.

PR Close #59024
2025-01-16 09:22:46 -08:00
Matthieu Riegler
901fd1c09b fix(core): Ensure resource sets an error (#58855)
Before this commit, a resource with a previous value wouldn't set the error state correctly.
This commit fixes this. A resource will set its status to error even when there was a previous valid value.

PR Close #58855
2024-11-25 15:28:17 +00:00
Alex Rickabaugh
18d8d44b1f feat(core): experimental resource() API for async dependencies (#58255)
Implement a new experimental API, called `resource()`. Resources are
asynchronous dependencies that are managed and delivered through the signal
graph. Resources are defined by their reactive request function and their
asynchronous loader, which retrieves the value of the resource for a given
request value. For example, a "current user" resource may retrieve data for
the current user, where the request function derives the API call to make
from a signal of the current user id.

Resources are represented by the `Resource<T>` type, which includes signals
for the resource's current value as well as its state. `WritableResource<T>`
extends that type to allow for local mutations of the resource through its
`value` signal (which is therefore two-way bindable).

PR Close #58255
2024-10-21 13:25:58 -07:00