connectedObservable()

Observable creation operator

Observes the connection state of a Stencil component to the DOM.

Connected observable is just a simple wrapper around Stencil’s connectedCallback() and disconnectedCallback() lifecycle methods which emits value when component is connected to the DOM, or disconnected from it. When created, current state of component is immediately emitted.

Uses hot observable pattern, which means that the observable is shared between all subscribers and emits the same value to all of them.

This observable has little real world use cases, however, it is used internally for other operators.

connectedObservable(cmp)

Creates an observable emitting the connection state of a Stencil component.

function connectedObservable(cmp: ComponentInterface): Observable<boolean>;
Arguments:
  • cmp (ComponentInterface) – The Stencil component instance to observe.

Returns:

Observable that emits true when the component is connected to the DOM and false when it is disconnected.

Return type:

Observable<boolean>

Example

Process window scroll events only when component is connected to the DOM
 1import {
 2    Component,
 3    ComponentInterface,
 4    h,
 5} from '@stencil/core';
 6import { connectedObservable } from '@runopenode/rxjs-stencil';
 7import { fromEvent, Observable } from 'rxjs';
 8import { filter, switchMap } from 'rxjs/operators';
 9
10@Component({
11    tag: 'my-cmp',
12    shadow: true,
13})
14class MyCmp implements ComponentInterface {
15
16    public constructor() {
17         connectedObservable(this)
18             .pipe(
19                 filter((isConnected: boolean): boolean => isConnected),
20                 switchMap((): Observable<Event> => fromEvent(window, 'scroll')),
21             )
22             .subscribe((event: Event): void => {
23                 // Handle scroll event
24             });
25    }
26
27    public render(): any {
28        // Render component template
29    }
30}