GithubNPM
Options
All
  • Public
  • Public/Protected
  • All
Menu

Package containing utility operators for use with RxJS covering various categories such as side effects, handling streams and converting values.

Utility Module

Type aliases

CallbackFn<T>: (...args: T[]) => void

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

Type parameters

  • T: unknown

    The type of the value from a source

Type declaration

    • (...args: T[]): void
    • Parameters

      • Rest ...args: T[]

      Returns void

MapFn<T, K>: (value: T) => K

A function used to map values to a modified value, either of the same type (String.toUpperCase) or of a different type (Number.parseInt)

example

Map a string to a number

const mapToNumber: MapFn<string, number> = (input: string): number => parseInt(input);
example

Map any string to an upper case string

const mapToNumber: MapFn<string> = (input: string): string => input.toUpperCase();

Type parameters

  • T = unknown

    The type of value as input to the method

  • K = T | unknown

    The type of value returned from the method

Type declaration

    • (value: T): K
    • Parameters

      • value: T

      Returns K

PredicateFn<T>: (...args: T[]) => boolean

A function that takes one or more parameters and returns a boolean value based on the function calculation

example

Return is a number is boolean true

const isTruthy: PredicateFn<number> = (item: number) => Boolean(number);
example

Return is a number is greater than 10

const isTruthy: PredicateFn<number> = (item: number) => item > 10;
example

Return if two numbers match

const isTruthy: PredicateFn<number> = (item1: number, item2: number) => item1 === item2;

Type parameters

  • T: unknown

    The type of the value being checked

Type declaration

    • (...args: T[]): boolean
    • Parameters

      • Rest ...args: T[]

      Returns boolean

QueryMethod<T>: (query: string) => ObservableInput<T>

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

Type parameters

  • T = unknown

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

Type declaration

    • (query: string): ObservableInput<T>
    • Parameters

      • query: string

      Returns ObservableInput < T >

Colour Functions

  • hexToRGBA(alpha?: Subscribable<number> | number): MonoTypeOperatorFunction<string>
  • Returns an Observable that emits a string containing a rgb or rgba colour (if alpha is included in the sting or as a property) converted from a source hex string

    example

    Returns rgb results from hex colour strings

    const input = ['#000000', '#ffffff', '#00ff00'];
    from(input).pipe(hexToRGBA()).subscribe();
    

    Output: 'rgb(0, 0, 0)', 'rgb(255, 255, 255)', 'rgb(0, 255, 0)'

    example

    Returns rgba results from hex colour strings with opacity

    const input = ['#000000', '#ffffff', '#00ff00'];
    from(input).pipe(hexToRGBA(0.5)).subscribe();
    

    Output: 'rgba(0, 0, 0, 0.5)', 'rgba(255, 255, 255, 0.5)', 'rgba(0, 255, 0, 0.5)'

    example

    Returns rgba results from hex colour strings

    const input = ['000000ff', 'ffffff80', '00ff00e6'];
    from(input).pipe(hexToRGBA()).subscribe();
    

    Output: 'rgba(0, 0, 0, 1)', 'rgba(255, 255, 255, 0.5)', 'rgba(0, 255, 0, 0.9)'

    Parameters

    • Optional alpha: Subscribable<number> | number

      Optional Alpha to include if converting 3-part hex colours to rgba

    Returns MonoTypeOperatorFunction < string >

    Observable that emits a string containing a HTML hex colour

  • rgbToHex(excludeHash?: Subscribable<boolean> | boolean): MonoTypeOperatorFunction<string>
  • Returns an Observable that emits a string containing a HTML hex colour converted from a source rgb string

    example

    Returns hex results from rgb colour strings

    const input = ['rgb(0,0,0)', 'rgb(255,255,255)', 'rgb(0,255,0)'];
    from(input).pipe(rgbToHex()).subscribe();
    

    Output: '#000000', '#ffffff', '#00ff00'

    example

    Returns hex results from rgb colour strings excluding hash

    const input = ['rgb(0,0,0)', 'rgb(255,255,255)', 'rgb(0,255,0)'];
    from(input).pipe(rgbToHex(true)).subscribe();
    

    Output: '000000', 'ffffff', '00ff00'

    Parameters

    • Optional excludeHash: Subscribable<boolean> | boolean

      Optional boolean to exclude the hash (#) character from the return result

    Returns MonoTypeOperatorFunction < string >

    Observable that emits a string containing a HTML hex colour

  • rgbaToHex(excludeHash?: Subscribable<boolean> | boolean): MonoTypeOperatorFunction<string>
  • Returns an Observable that emits a string containing a HTML hex colour converted from a source rgba string

    example

    Returns hex results from rgba colour strings

    const input = ['rgba(0,0,0,1)', 'rgba(255,255,255,0.5)', 'rgba(0,255,0,0.9)'];
    from(input).pipe(rgbaToHex()).subscribe();
    

    Output: '#000000ff', '#ffffff80', '#00ff00e6'

    example

    Returns hex results from rgba colour strings excluding hash

    const input = ['rgba(0,0,0,1)', 'rgba(255,255,255,0.5)', 'rgba(0,255,0,0.9)'];
    from(input).pipe(rgbaToHex(true)).subscribe();
    

    Output: '000000ff', 'ffffff80', '00ff00e6'

    Parameters

    • Optional excludeHash: Subscribable<boolean> | boolean

      Optional boolean to exclude the hash (#) character from the return result

    Returns MonoTypeOperatorFunction < string >

    Observable that emits a string containing a HTML hex colour

Conversion Functions

  • length<I, O>(fromLength: Subscribable<I> | I, toLength: Subscribable<O> | O, precision?: Subscribable<number> | number): MonoTypeOperatorFunction<number>
  • Returns an Observable that converts the source value through Lengths conversion

    example

    Convert a value from Miles to Meters

    const source$ = from([100, 200, 300, 500]);
    
    source$.pipe(length(Lengths.MILES, Lengths.METERS, 0)).subscribe()
    

    Output: 160934, 321869, 482803, 804672

    example

    Convert a value from Inches to Yards to precision 2

    const source$ = from([100, 200, 300, 500]);
    
    source$.pipe(length('inches', 'yards', 2)).subscribe()
    

    Output: 2.78, 5.56, 8.33, 13.89

    Type parameters

    • I: SupportedLengths

    • O: SupportedLengths

    Parameters

    • fromLength: Subscribable<I> | I

      The length type of the source value

    • toLength: Subscribable<O> | O

      The length type of the output value

    • precision: Subscribable<number> | number = 3

      The number of decimal places to return, default is 3

    Returns MonoTypeOperatorFunction < number >

    Observable that emits a number that is the from Lengths converted to the to Lengths

  • temperature<I, O>(fromTemperature: Subscribable<I> | I, toTemperature: Subscribable<O> | O, precision?: Subscribable<number> | number): MonoTypeOperatorFunction<number>
  • Returns an Observable that emits a number based on the version of the source value through Temperatures conversion

    remarks

    This operator does not handle validation on temperature values (e.g. negative Kelvin values)

    example

    Convert a source of numbers from Celsius to Fahrenheit

    const source$ = from([0, 100, 37.5, -42]);
    
    source$.pipe(temperature(Temperatures.CELSIUS, Temperatures.FAHRENHEIT)).subscribe()
    

    Output: 32, 212, 99.5, -43.6

    example

    Convert a source of numbers from Kelvin to Celsius with precision 2

    const source$ = from([0, 100, 273.15, 10000]);
    
    source$.pipe(temperature('kelvin', 'celsius', 2)).subscribe()
    

    Output: -273,15, -173.15, 0, 9726.85

    Type parameters

    • I: SupportedTemperatures

      String or Temperatures value for the input value

    • O: SupportedTemperatures

      String or Temperatures value for the output value

    Parameters

    • fromTemperature: Subscribable<I> | I

      The temperature type to convert from

    • toTemperature: Subscribable<O> | O

      The temperature type to convert from

    • precision: Subscribable<number> | number = 2

      The number of decimal places to return, default is 1

    Returns MonoTypeOperatorFunction < number >

    Observable that emits a number that is the from Temperatures converted to the to Temperatures

  • weight<I, O>(fromWeight: Subscribable<I> | I, toWeight: Subscribable<O> | O, precision?: Subscribable<number> | number): MonoTypeOperatorFunction<number>
  • Returns an Observable that converts the source value through Weights conversion

    example

    Convert Grams to Kilograms

    const source$ = from([10, 5, 100]);
    
    source$.pipe(weight(Weights.GRAMS, Weights.KILOGRAMS)).subscribe()
    

    Output: 0.01, 0.05, 0.1

    example

    Convert Kilograms to Stone with a precision of 1

    const source$ = from([10, 5, 100]);
    
    source$.pipe(weight('st', 'kg', 1)).subscribe()
    

    Output: 63.5, 31.8, 635

    Type parameters

    • I: SupportedWeights

      String or Weights value for the input value

    • O: SupportedWeights

      String or Weights value for the output value

    Parameters

    • fromWeight: Subscribable<I> | I

      The weight type of the source value

    • toWeight: Subscribable<O> | O

      The weight type of the output value

    • precision: Subscribable<number> | number = 2

      The number of decimal places to return, default is 2

    Returns MonoTypeOperatorFunction < number >

    Observable that emits a number that is the from Weights converted to the to Weights

HTTP Functions

  • 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

    • init: RequestInit = ...

      Optional RequestInit dictionary

    • controller: AbortController = ...

      Optional AbortController used to cancel any outstanding requests

    Returns Observable < number | Uint8Array >

Mapping 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: unknown

      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

  • mapIf<I, T, F>(predicate: PredicateFn<I>, trueResult: MapFn<I, T>, falseResult: MapFn<I, 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 = unknown

      The type returned from the Truthy result

    • F = unknown

      The type returned from the Falsy result

    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, Subscribable<T>>, falseResult: MapFn<I, Subscribable<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 = unknown

      The type returned from the Truthy result

    • F = unknown

      The type returned from the Falsy result

    Parameters

    • predicate: PredicateFn<I>

      The method to check the value from the source Observable

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

      The method with return value for a truthy PredicateFn

    • falseResult: MapFn<I, Subscribable<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

Side Effects Functions

  • 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<undefined>): MonoTypeOperatorFunction<T>
  • Perform a side effect for the first subscription to the source Observable, return an Observable that is identical to the source.

    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<undefined>): 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

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

    example

    Perform a side effect on every new unsubscription to a source

    const onClick$ = fromEvent(element, 'click').pipe(tapOnUnsubscribe(( ) => console.log('End Subscription')));
    
    onClick$.pipe(take(1)).subscribe();
    onClick$.pipe(take(1)).subscribe();
    

    Output: 'End Subscription', 'End Subscription'

    Type parameters

    • T: unknown

      The value type of the source

    Parameters

    Returns MonoTypeOperatorFunction < T >

    Observable that emits the source Observable and calls the callback on unsubscription

Streams Functions

  • fromEventSource<T>(source: EventSource, eventName?: string, openObserver?: Observer<Event>, signal?: AbortSignal): Observable<T>
  • Returns an Observable that emits values from an EventSource subscribing to the the passed eventName stream. Takes an optional Observer (e.g. Subject) to emit when the stream opens

    see

    RxJS Event Source Example

    example

    Subscribe to an EventSource, listen for it opening and provide a stop signal

    // The event source emits a time every 1 minute
    const eventSource = new EventSource('/event-stream');
    const stopSource = new AbortController();
    const isOpen$ = new Subject<Event>();
    
    function endSource() {
      stopSource.abort();
    }
    
    fromEventSource<string>(eventSource, 'message', isOpen$, stopSource.signal).pipe(
     tap(value => {
       const parsed = JSON.parse(value);
       outputSpan.innerHTML = `The time is ${parsed.message}`
     }),
     finalize(() => {
       outputSpan.innerHTML = `EventSource closed`
     })
    ).subscribe();
    

    Output: 'The time is 12:01', 'The time is 12:02', ....

    Type parameters

    • T: unknown

      The type of the value in the message data property

    Parameters

    • source: EventSource

      The event source to subscribe to

    • eventName: string = 'message'

      The name of the event to listen to, by default this is message

    • Optional openObserver: Observer<Event>

      Optional observer that is emitted when the event source is opened

    • Optional signal: AbortSignal

      Optional signal to end the event source

    Returns Observable < T >

    Observable that emits the data value from an EventSource message

  • 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

    • 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

  • fromWebSerial(port: SerialPort, writerSource?: Observable<Uint8Array>, options?: SerialOptions, signal?: AbortSignal): Observable<Uint8Array>
  • Returns an Observable that emits the response from a source connected to via the Web Serial API. The function can also accept an Observable that emits values to write to the serial device, allowing two-way communication.

    Both the input and output values must be Uint8Array, you can use TextEncoder and TextDecoder to convert between strings, which can be seen in the demo

    The function will also handle opening and closing of the port from the serial device when using an AbortSignal or ending the RxJS subscription.

    remarks

    Web Serial is available in Chrome or Edge 89 or later, in earlier versions it can be enabled using the experimental web features flag. To use the feature is must be invoked with a user action such as a user button click, and in a browser location that provides an acceptable policy before the port can be opened by this operator.

    see

    RxJS Web Serial Demo

    see

    Demo Source

    Parameters

    • port: SerialPort

      The SerialPort object to connect to

    • Optional writerSource: Observable<Uint8Array>

      Optional Observable source to emit values to the serial connection writer

    • Optional options: SerialOptions

      Options for the connection - if none passed a default baudRate of 9600 is set

    • Optional signal: AbortSignal

      Optional signal to end the source

    Returns Observable < Uint8Array >

    Observable that emits the output from a serial source

  • 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

Subscription Functions

  • takeUntilSignal<T>(signal: AbortSignal): MonoTypeOperatorFunction<T>
  • Returns the source Observable that will use the passed AbortSignal to handle unsubscription

    example

    Pass a signal to handle unsubscription

    const stop = new AbortController();
    
    const source$ = from([1, 2, 3, 4, 5]);
    
    source.pipe(takeUntilSignal(stop.signal)).subscribe();
    

    Type parameters

    Parameters

    • signal: AbortSignal

      The signal used to end the subscription

    Returns MonoTypeOperatorFunction < T >

    Observable that will end subscription when the AbortSignal has been fired

Generated using TypeDoc, the 18/11/2022 at 13:22:58