Options
All
  • Public
  • Public/Protected
  • All
Menu

Module - Utility

Type aliases

CallbackFn<T>: function

A callback function that is called with 0...n arguments

internal
params

args Arguments passed to the callback

returns

void

Type parameters

  • T: unknown

    The type of the value from a source

Type declaration

MapFn<T, K>: function

A map function is used to convert values, usually using Array.map - the values can be of the same type (such as multiplying and number or using String.toUpperCase) or it can change to a different value (using Number.parseInt or Number.toString)

Example map functions:

function mapToUpperCase(str: string): string {
 return str.toUpperCase();
}

function mapToInteger (str: string): number {
 return parseInt(str, 10);
}
internal
param

The value to be converted

returns

A value that has been mapped to a new value

Type parameters

  • T

    The type of the value from the input source

  • K

    The type of the returned from the new Observable source

Type declaration

PredicateFn<T>: function

A predicate function is used when you need a boolean check of a value, usually with Array.filter or Array.find

Example predicate function:

function isGreaterThan5(item: unknown): boolean {
 return typeof item === 'number' && item > 5
}
internal
param

The arguments for the function

returns

A boolean value from the value being checked in the predicate

Type parameters

  • T: unknown

    The type of the value being checked

Type declaration

QueryMethod<T>: function

A function passed to debounceWithQuery as the second parameter, takes a string and returns an Observable source

internal
param

The string to send to the query method

Type parameters

  • T

    The response from an API which returns the result of a query

Type declaration

Functions

  • debounceWithQuery<T>(time: number, queryMethod: QueryMethod<T>): OperatorFunction<string, T>
  • Returns an Observable value from a remote source where the QueryMethod returns a result such as a search from a remote location

    example

    On keypress of an input pass value and debounce for 500ms before sending to remote server request

    const doQuery = (query: string) => http.get(`/search?query=${query}`);
    fromEvent(input, 'keyup').pipe(map(event => event.target.value), debounceWithQuery(500, doQuery)).subscribe();

    Output: A valid server response containing search results

    Type parameters

    • T

      The response from an API which returns the result of a query

    Parameters

    • time: number

      The debounce time before the query method is executed

    • queryMethod: QueryMethod<T>

      The method that returns the search

    Returns OperatorFunction<string, T>

    An Observable that emits a value from a server request

  • decodeJWT<T>(): OperatorFunction<string, T>
  • Returns an Observable that emits an object from a parsed JWT token

    example

    Parse a JWT token and return the decoded body

    const input =
      'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c';
      of(input).pipe(decodeJWT()).subscribe()

    Output: { "sub": "1234567890", "name": "John Doe", "iat": 1516239022}

    Type parameters

    • T: Record<string, unknown>

      The known JWT response object

    Returns OperatorFunction<string, T>

    Observable that emits a decoded JWT token body

  • fromFetchWithProgress(input: RequestInfo, init?: RequestInit, controller?: AbortController): Observable<number | Uint8Array>
  • Returns an Observable from fetch that emits a number during the progress of the file download and once finished emits a Uint8Array

    see

    Demo Image Loader

    example

    Set up fetching a large image, show a progress and image on final load

    const image = document.querySelector(".image") as HTMLImageElement;
    const progress = document.querySelector(".progress") as HTMLSpanElement;
    
    progress.innerHTML = "0%";
    
    fromFetchWithProgress("https://example.com/large-image.jpg").pipe(
     tap(val => {
       if (typeof val === "number") {
         progress.innerHTML = `${Math.round(val * 100)}%`;
       }
     }),
     filter(val => val instanceof Uint8Array),
     tap((val: Uint8Array) => {
       const img = URL.createObjectURL(
         new Blob([val.buffer], { type: "image/png" })
       );
       image.src = img;
     }),
     catchError(error => {
       progress.innerHTML = error;
       return throwError(undefined);
     })).subscribe();

    Parameters

    • input: RequestInfo

      A string url or Request object

    • Default value init: RequestInit = {}

      Optional RequestInit dictionary

    • Default value controller: AbortController = new AbortController()

      Optional AbortController used to cancel any outstanding requests

    Returns Observable<number | Uint8Array>

  • fromReadableStream<T>(stream: ReadableStream<T>, signal?: AbortSignal, queueStrategy?: QueuingStrategy, throwEndAsError?: boolean): Observable<T>
  • Creates an Observable source from a ReadableStream source that will emit any values emitted by the stream.

    see

    StreamAPI Number Stream

    see

    Fetch + StreamAPI Demo

    example

    Create a ReadableStream of 0 to 100 and convert to an Observable

    const stream = new ReadableStream({
      start: (controller) => {
       for (let i = 0; i <100; i++) {
         controller.enqueue(i)
       }
       controller.close();
      }
    });
    
    fromReadableStream(stream).pipe(reduce((a, b) => a + b)).subscribe();

    Output: 4950

    Type parameters

    • T: unknown

    Parameters

    • stream: ReadableStream<T>

      The ReadableStream to subscribe to

    • Optional signal: AbortSignal

      Optional AbortSignal to provide to the underlying stream

    • Optional queueStrategy: QueuingStrategy

      Optional strategy for backpressure queueing

    • Default value throwEndAsError: boolean = false

      Optional to return an error when the AbortSignal has been fired instead of just closing

    Returns Observable<T>

    Observable that emits from a ReadableStream source

  • mapIf<I, T, F>(predicate: PredicateFn<I>, trueResult: MapFn<I, T>, falseResult: MapFn<I, T | F>): OperatorFunction<I, T | F>
  • Returns an Observable that emits the value from either the trueResult or falseResult based on the result from the source with a PredicateFn.

    remarks

    Each method can return it's own type which you should handle in later operators

    example

    Returns a FizzBuzz based on the input value

    const input = [ 1, 2, 3, 4, 5, 6, 10, 15, 16 ];
    from(input).pipe(
     mapIf<number, string, number>(
       (value) => value % 15 == 0 || value % 3 == 0 || value % 5 == 0,
       (value) => (value % 15 == 0 ? `FizzBuzz` : value % 3 === 0 ? 'Fizz' : 'Buzz'),
       (value) => value,
     ),
    ).subscribe();

    Output: 1, 2, 'Fizz', 4, 'Buzz', 'Fizz', 10, 'FizzBuzz', 16

    Type parameters

    • I: unknown

      The type of value from the source

    • T

      The type returned from the Truthy result

    • F

      The type returned from the Falsy result, this type is optional and if not included the T type will be used

    Parameters

    Returns OperatorFunction<I, T | F>

    Observable that emits a value from the truthy or falsy MapFn based on the PredicateFn result

  • switchMapIf<I, T, F>(predicate: PredicateFn<I>, trueResult: MapFn<I, Observable<T>>, falseResult: MapFn<I, Observable<T | F>>): OperatorFunction<I, T | F>
  • Returns an Observable that emits the value from either the trueResult or falseResult based on the result from the source with a PredicateFn.

    remarks

    Each method can return it's own type which you should handle in later operators

    example

    Returns a FizzBuzz based on the input value

    const input = [ 12, 5, 6, 1, 3, 10 ];
    from(input).pipe(
     switchMapIf<number, boolean>(
       (value) => value <= 6,
       (value) => of(true),
       (value) => of(false),
     ),
    ).subscribe();

    Output: true, false, true, false, false, true

    Type parameters

    • I: unknown

      The type of value from the source

    • T

      The type returned from the Truthy result

    • F

      The type returned from the Falsy result, this type is optional and if not included the T type will be used

    Parameters

    • predicate: PredicateFn<I>

      The method to check the value from the source Observable

    • trueResult: MapFn<I, Observable<T>>

      The method with return value for a truthy PredicateFn

    • falseResult: MapFn<I, Observable<T | F>>

      The method with return value for a falsy PredicateFn

    Returns OperatorFunction<I, T | F>

    Observable that emits a value based on the PredicateFn result

  • Perform a side effect for every emit from the source Observable that passes the PredicateFn, return an Observable that is identical to the source.

    example

    Perform a side effect when the value is mod2

    const predicateFn = (value: number) => value % 2 === 0;
    const callbackFn = (value: number) => `${value} is mod2`)
    
    const input = [1, 2, 3, 4, 5, 6];
    from(input).pipe(tapIf(predicateFn, callbackFn).subscribe();

    Output: '2 is mod2', '4 is mod2', '6 is mod2'

    Type parameters

    • T: unknown

      The value type of the source

    Parameters

    Returns MonoTypeOperatorFunction<T>

    Observable that emits the source observable after performing a side effect

  • tapOnFirstEmit<T>(callback: CallbackFn<T>): MonoTypeOperatorFunction<T>
  • Perform a side effect for the first subscription to the source Observable, return an Observable that is identical to the source.

    example
    form.valueChange.pipe(tapOnFirstEmit(() => this.onTouch())).subscribe();
    example

    Perform a side effect on first subscription to the source

    const input = ['Hello', 'RxJS', 'Ninja'];
    const echoValue = value => `First value is ${value}`;
    
    from(input).pipe(tapOnFirstEmit(echoValue)).subscribe();

    Output: Hello

    Type parameters

    • T: unknown

      The value type of the source

    Parameters

    Returns MonoTypeOperatorFunction<T>

    Observable that emits the source observable after performing a side effect

  • tapOnSubscribe<T>(callback: CallbackFn<T>): MonoTypeOperatorFunction<T>
  • Perform a side effect for every subscription to the source Observable and return an Observable that is identical to the source.

    example

    Perform a side effect on every new subscription to a source

    const onClick$ = fromEvent(element, 'click').pipe(tapOnSubscribe(( ) => console.log('New Subscription')));
    
    onClick$.subscribe();
    onClick$.subscribe();

    Output: 'New Subscription', 'New Subscription'

    Type parameters

    • T: unknown

      The value type of the source

    Parameters

    Returns MonoTypeOperatorFunction<T>

    Observable that emits the source observable after performing a side effect

  • toWritableStream<T>(stream: WritableStream<T> | WritableStreamDefaultWriter<T>, signal?: AbortSignal): MonoTypeOperatorFunction<T>
  • Returns the source Observable, emitting it through the passed WritableStream and handling the internal subscription state and error handling. If passed an AbortSignal the WritableStream can be ended early without ending the entire subscription

    see

    Writable Stream Demo

    example

    Write an array of Observable values to a WritableStream

    let result = ''
    const stream = new WritableStream({
      write: (chunk) => result += chunk,
      close: () => console.log(result)
    });
    
    const input = ['Hello', ' ', 'RxJS', ' ', 'Ninja'];
    from(input).pipe(toWritableStream(stream)).subscribe();

    Output: Hello RxJS Ninja

    Type parameters

    • T: unknown

    Parameters

    • stream: WritableStream<T> | WritableStreamDefaultWriter<T>

      The Writer object to emit the data to

    • Optional signal: AbortSignal

      Optional signal used to end the writer without ending the rest of the stream

    Returns MonoTypeOperatorFunction<T>

    Observable that emits the source observable after performing a write to the WritableStream

Generated using TypeDoc, the 1/19/2021 at 12:42:11 AM