@angular/core#Predicate TypeScript Examples

The following examples show how to use @angular/core#Predicate. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: filter-behavior.ts    From s-libs with MIT License 6 votes vote down vote up
/**
 * Works like `filter()`, but always lets through the first emission for each new subscriber. This makes it suitable for subscribers that expect the observable to behave like a `BehaviorSubject`, where the first emission is processed synchronously during the call to `subscribe()` (such as the `async` pipe in an Angular template).
 *
 * ```
 * source:                   |-false--true--false--true--false--true-|
 * filterBehavior(identity): |-false--true---------true---------true-|
 * filterBehavior(identity):        |-true---------true---------true-|
 * filterBehavior(identity):              |-false--true---------true-|
 * ```
 */
export function filterBehavior<T>(
  predicate: Predicate<T>,
): MonoTypeOperatorFunction<T> {
  return createOperatorFunction<T>((subscriber, destination) => {
    let firstValue = true;
    subscriber.next = (value): void => {
      if (firstValue) {
        destination.next(value);
        firstValue = false;
        return;
      }

      try {
        if (predicate(value)) {
          destination.next(value);
        }
      } catch (ex) {
        destination.error(ex);
      }
    };
  });
}