Skip to content

Allow rxResource's request fn to handle Observable triggers #58854

Closed as not planned

Description

@markostanimirovic

Which @angular/* package(s) are relevant/related to the feature request?

core

Description

Currently, rxResource's request function doesn't support returning an Observable that can trigger the loader function when new values are emitted.

Workaround:

const dataService = inject(DataService);
const click$ = new Subject<MouseEvent>();
const click = toSignal(click$, { initialValue: null });
const data = rxResource({
  request: click,
  loader: ({ request }) =>
    request ? dataService.getData() : of(null),
});

Proposed solution

Allow request to return an Observable, where each emission triggers the loader function:

const dataService = inject(DataService);
const click$ = new Subject<MouseEvent>();
const data = rxResource({
  request: () => click$,
  loader: () => dataService.getData(),
});

Benefits:

  • More reactive control over loader triggers
  • Better integration with event-based workflows
  • Reduced boilerplate when working with Observables

Alternatives considered

_

Activity

  1. added
    area: core
    core: reactivity
    on Nov 24, 2024
  2. added this to the needsTriage milestone on Nov 24, 2024
  3. blueiceprj commented on Nov 24, 2024

    @blueiceprj

    There is definitely a need for such a parameter to make the code cleaner and more understandable.

    .......
    
    shouldLoad: (parameters) => {
         return parameters.request.name !== ''  
    },
    
    ....
    
  4. JeanMeche commented on Nov 24, 2024

    @JeanMeche
    Member

    Sharing some thoughts on this:
    Having an observable as loader will introduce more complexity to rxResource,

    • The resource loading will be event based.
    • While waiting for the event we would have either be in status, Idle or loading, both wouldn't be correct. Should we introduce another status ?
    • As discussed in Add lazy property to ResourceOptions interface #58422, resource isn't designed to be lazy, which this change would somehow introduce
    • using toSignal(myObs$, {initialValue: ...}) is more explicit, not event based and the request value can be read synchronously

    Happy to be challenged on this, of course.

  5. samuelfernandez commented on Nov 25, 2024

    @samuelfernandez

    Sharing some thoughts on this:
    Having an observable as loader will introduce more complexity to rxResource,

    • The resource loading will be event based.
    • While waiting for the event we would have either be in status, Idle or loading, both wouldn't be correct. Should we introduce another status ?
    • As discussed in Add lazy property to ResourceOptions interface #58422, resource isn't designed to be lazy, which this change would somehow introduce
    • using toSignal(myObs$, {initialValue: ...}) is more explicit, not event based and the request value can be read synchronously

    Happy to be challenged on this, of course.

    Being lazy and event based seems the next step if used in route resolvers. I feel that, if the integration with the router is addressed, the full API for resource will emerge.

  6. alxhub commented on Nov 25, 2024

    @alxhub
    Member

    I'm sure we'll discuss this more, but a few initial thoughts:

    The ternary in request ? dataService.getData() : of(null) is unnecessary - resource() (and rxResource()) already suspend themselves when request is undefined, so if that's used instead of null as the initial value then the loader will never be called and the resource will stay Idle until the request is defined.

    More generally, though, resource is meant to align conceptually with computed signals. To create a computed signal you specify (declaratively) how to produce the value as a function of the current state, and the signal graph manages that derivation as the state changes. resource() functions similarly - you declare the loading request to make as a function of the current state, and the resource updates automatically as the application state changes.

    Using an event like button clicks to trigger data loading at a specific point in time is a different pattern entirely. If I were implementing a UI like this, I'd probably define the resource based on a computed request (or none if the request is static) and then call .reload() on every button click. Doing this will also have proper debouncing behavior, as refresh() is a no-op if reloading is already in progress, but changing the request cancels the in-progress load.

  7. e-oz commented on Nov 25, 2024

    @e-oz

    Sorry for offtopic, but how you check the status in the template?

    I tried

    @if (res.status() === 'loading'
    

    And IDE said that I can’t use strings.
    Am I supposed to use numbers in this case?
    Because importing an enum just to reference it in the template looks like overkill.

  8. pkozlowski-opensource commented on Nov 26, 2024

    @pkozlowski-opensource
    Member

    @alxhub already covered several things I wanted to mention, but I would like to further expand on one of the suggested benefits:

    Better integration with event-based workflows

    Here is the thing: resource was designed for data-based workflows. You set a state and and resource responds to changes in the state. With all the semantics that we already know from a computed - just that the computation is different / async. As Alex mention, event-based workflows are a completely different thinking and technical construct. IMO resource is not a good fit for those architectures - in the sense that it provides more friction than value.

    I would suggest coming up with a different primitive for the event-based architectures.

  9. JeanMeche commented on Nov 26, 2024

    @JeanMeche
    Member

    @e-oz You likely won't reach often for that status in the template. The loading status can be checked via the computed myResource. isLoading().

  10. samuelfernandez commented on Nov 26, 2024

    @samuelfernandez

    @alxhub already covered several things I wanted to mention, but I would like to further expand on one of the suggested benefits:

    Better integration with event-based workflows

    Here is the thing: resource was designed for data-based workflows. You set a state and and resource responds to changes in the state. With all the semantics that we already know from a computed - just that the computation is different / async. As Alex mention, event-based workflows are a completely different thinking and technical construct. IMO resource is not a good fit for those architectures - in the sense that it provides more friction than value.

    I would suggest coming up with a different primitive for the event-based architectures.

    As I understand this explanation, does it mean that resource is only a fit for loading data, aka GET requests? For loading, the declarative solution works great. But other verbs, such as POST or DELETE make sense when reacting to events.

    Another question, what about the scenario where you want to define the request, but the source is defined later on? Example: the loader lives in a service, but the request params come from a component. How do you envision passing the request reference to the resource?

  11. pkozlowski-opensource commented on Nov 27, 2024

    @pkozlowski-opensource
    Member

    As I understand this explanation, does it mean that resource is only a fit for loading data, aka GET requests? For loading, the declarative solution works great. But other verbs, such as POST or DELETE make sense when reacting to events.

    @samuelfernandez yes, the idea of the resource is to represent data from the external story (regardless of the exact HTTP method used). As of today the resource doesn't have the change / mutation story for the external data sources.

    Another question, what about the scenario where you want to define the request, but the source is defined later on? Example: the loader lives in a service, but the request params come from a component. How do you envision passing the request reference to the resource?

    I believe that the current resource design covers this use-case - it takes 2 functions, regardless of where those are defined. unless I'm misunderstanding your question - a more concrete example would be needed.

  12. samuelfernandez commented on Nov 29, 2024

    @samuelfernandez

    As I understand this explanation, does it mean that resource is only a fit for loading data, aka GET requests? For loading, the declarative solution works great. But other verbs, such as POST or DELETE make sense when reacting to events.

    @samuelfernandez yes, the idea of the resource is to represent data from the external story (regardless of the exact HTTP method used). As of today the resource doesn't have the change / mutation story for the external data sources.

    Another question, what about the scenario where you want to define the request, but the source is defined later on? Example: the loader lives in a service, but the request params come from a component. How do you envision passing the request reference to the resource?

    I believe that the current resource design covers this use-case - it takes 2 functions, regardless of where those are defined. unless I'm misunderstanding your question - a more concrete example would be needed.

    @pkozlowski-opensource thanks for the clarification regarding mutation changes, looking forward to see how ends up being implemented 😄

    Practical example of my second point: a service is used to load the data, a component uses that service to access the resource:

    @Injectable({ providedIn: 'root')
    export class UserClient {
    // ...
      readonly userResource = resource({
        request: () => /* This depends on a query param from the url */,
        loader: (request) => this.http.get(request.userId),
      });
    }
    
    @Component() // Routed component
    class User {
      protected readonly userClient = inject(UserClient);
      
      readonly userId = input<string>(); // This is derived with withComponentInputBinding()
    
      // How to pass the userId signal to the resource in the service?
    }

    I can think on two possible solutions:

    • First, internal signal to keep the request params, but it somehow defeats the "derived" nature of resource since it needs to work through imperative code:
    @Injectable({ providedIn: 'root')
    export class UserClient {
    // ...
      private readonly userId = signal<string | undefined>(undefined);
    
      readonly userResource = resource({
        request: () => this.userId() != null ? { userId: this.userId() } : undefined,
        loader: (request) => this.http.get(request.userId),
      });
    
      loadUser(userId: string) {
        this.userId.set(userId)
      }
    }
    
    @Component() // Routed component
    class User {
      protected readonly userClient = inject(UserClient);
      
      readonly userId = input<string>(); // This is derived with withComponentInputBinding()
    
      constructor() {
        effect(() => this.userClient.loadUser(this.userId()));
      } 
    }
    • Let the service be a resource factory:
    @Injectable({ providedIn: 'root')
    export class UserClient {
    // ...
      getUserResource(userId: Signal<string>) {
        return resource({
          request: () => ({ userId: userId() }),
          loader: (request) => this.http.get(request.userId),
        });
      }
    }
    
    @Component() // Routed component
    class User {
      protected readonly userClient = inject(UserClient);
      
      readonly userId = input<string>(); // This is derived with withComponentInputBinding()
    
      readonly userResource = this.userClient.getUserResource(this.userId);
    }

    I might have answered myself, maybe the resource factory pattern is the best in these scenarios..

  13. markostanimirovic commented on Dec 9, 2024

    @markostanimirovic
    ContributorAuthor

    Thank you all for sharing your thoughts! It seems this feature request is not in accordance with the rxResource design/future plans so I'm going to close it.

    I wish we had an RFC for resource/rxResource. Many new ideas/challenges would emerge I guess.

    Anyway, the overall design looks good to me, except for the name of the request property. When I saw request and loader for the first time, I was not sure which callback was the right place for sending HTTP requests. 👀 Consider renaming request to source, payload, or trigger.

  14. JeanMeche commented on Dec 9, 2024

    @JeanMeche
    Member

    Note, an RFC is planned for early next year. We first want to make sure many developers have the time to put their hands on that new API, to provide valuable feedback when we open the RFC.

  15. angular-automatic-lock-bot commented on Jan 9, 2025

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  16. locked and limited conversation to collaborators on Jan 9, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corecore: reactivitycross-cutting: signals

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions