untilDisconnected()

Pipeable operator

Operator that unsubscribes from the source observable when the component is disconnected from DOM.

Attention

This is the MOST IMPORTANT operator in this library. If you are using observables in your Stencil component, you SHOULD use this operator, whenever is possible, to avoid memory leaks when component is removed from DOM.

Tip

Good practice is to use this operator as the last operator in the pipe.

Tip

If you subscribe to an observable when component is connected to DOM, operator will unsubscribe from the observable when component is disconnected from DOM. If component is garbage collected, this will prevent memory leaks. If component is reconnected to DOM, since you are subscribing to the observable in the connectedCallback() method, you will be subscribed again to the observable.

untilDisconnected(cmp)

Creates a pipeable operator that unsubscribes from the source observable when the component is disconnected from DOM.

function untilDisconnected<T = unknown>(cmp: ComponentInterface): MonoTypeOperatorFunction<T>
Arguments:
  • cmp (ComponentInterface) – The Stencil component instance for which to unsubscribe from the source observable when disconnected from DOM.

Example

Complex example of using untilDisconnected() operator in a Stencil component.
 1import {
 2    Component,
 3    ComponentInterface,
 4} from '@stencil/core';
 5import { contentChildObservable, untilDisconnected } from '@runopenode/rxjs-stencil';
 6import { fromEvent, Observable } from 'rxjs';
 7import { filter, switchMap, map, debounceTime, distinctUntilChanged } from 'rxjs/operators';
 8import { fromFetch } from 'rxjs/fetch';
 9
10@Component({
11    tag: 'my-cmp',
12    shadow: true,
13})
14class MyCmp implements ComponentInterface {
15
16    public connectedCallback(): void {
17         contentChildObservable(this, 'input')
18             .pipe(
19                 filter((input: HTMLInputElement | null): input is HTMLInputElement => input !== null),
20                 switchMap((input: HTMLInputElement): Observable<Event> => fromEvent(input, 'input')),
21                 map((event: Event): string => (event.target as HTMLInputElement).value),
22                 debounceTime(300),
23                 distinctUntilChanged(),
24                 switchMap((value: string): Observable<Response> => fromFetch(`https://api.example.com/search?q=${value}`)),
25                 untilDisconnected(this), // Unsubscribe from the observable when component is disconnected from DOM
26             ).subscribe((response: Response): void => {;
27                 // Handle the response from the search API...
28             });
29    }
30}