Skip to content

Documentation(?): Way to filter multiple types #37

@mischkl

Description

@mischkl

For libraries such as redux-observable or @ngrx/effects it's a regular requirement to filter a stream of actions, which can be done with unionize like so:

this.actions$.pipe(
    filter(DomainActions.is.MY_DOMAIN_ACTION),
    ...
  );

and most of the time this is enough. However, sometimes it's necessary to filter according to multiple action types. At the moment this could be done with something like the following:

/** Example 1 **/

this.actions$.pipe(
    filter(action => 
      DomainActions.is.MY_DOMAIN_ACTION(action as DomainActions._Union) ||
      AnotherDomainActions.is.ANOTHER_DOMAIN_ACTION(action as AnotherDomainActions._Union))
    ...
  );

or perhaps:

/** Example 2 **/

this.actions$.pipe(
    filter(testMultiple(
      DomainActions.is.MY_DOMAIN_ACTION
      AnotherDomainActions.is.ANOTHER_DOMAIN_ACTION
    )),
    ...
  );

function testMultiple(...predicates: ((a: any) => boolean)[]) {
  return (a: any) => predicates.some(predicate => predicate(a));
}

Using something like the ngrx ofType operator this could be written as:

/** Example 3 **/

this.actions$.pipe(
    ofType(
      DomainActions.MY_DOMAIN_ACTION.name,
      AnotherDomainActions.ANOTHER_DOMAIN_ACTION.name
    ),
    ...
  );

but unfortunately the name property is undefined so I can't do that. 😦

So my question is, @pelotom or anyone else who might have an idea, what is the recommendation for such a case? Should I just create my own testMultiple() utility function à la example 2? Or is there some way to obtain the tag property as a string so I can do something like example 3? Or might there be some other way?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions