Options
All
  • Public
  • Public/Protected
  • All
Menu

External module "use-observable"

Index

Functions

Functions

useObservable

  • useObservable<State>(init: function): Observable<State>
  • useObservable<State, Inputs>(init: function, inputs: Inputs): Observable<State>
  • Accepts a function that returns an Observable. Optionally accepts an array of dependencies which will be turned into Observable and be passed to the init function.

    React function components will be called many times during its life cycle. Create or transform Observables in init function so that the operations won't be repeatedly performed.

    Node: useObservable will call init once and always return the same Observable. It is not safe to access closure variables (except Observables) directly inside init. You should pass them through the second argument as dependencies.

    Node: You can either pass or not pass a dependencies array but do not change to one another during Component's life cycle. The length of the dependencies array must also be fixed.

    Examples:

    interface CompProps {
      isOpen: boolean
    }
    
    const Comp: React.FC<CompProps> = props => {
      const [showPanel, setShowPanel] = useState(false)
    
      // Listen to props or state change
      const enhanced$ = useObservable(
        inputs$ => inputs$.pipe(map(([isOpen, showPanel]) => isOpen && showPanel)),
        [props.isOpen, showPanel]
      )
    }

    Create Observable

    const now$ = useObservable(
      () => interval(1000).pipe(
        map(() => new Date().toLocaleString())
      )
    )

    Transform Observables:

    // outers$ are created from other React-unrelated module
    const enhanced$ = useObservable(() => outers$.pipe(mapTo(false)))

    Mix them all together:

    const enhanced$ = useObservable(
      inputs$ => isEven$.pipe(
        withLatestFrom(inputs$),
        map(([isEven, [isOpen]]) => isEven && isOpen)
      ),
      [props.isOpen]
    )

    Type parameters

    • State

    Parameters

    • init: function

      A function that, when applied to an inputs Observable, returns an Observable.

        • (): Observable<State>
        • Returns Observable<State>

    Returns Observable<State>

  • Type parameters

    • State

    • Inputs: Readonly<any[]>

    Parameters

    • init: function

      A function that, when applied to an inputs Observable, returns an Observable.

        • (inputs$: Observable<Inputs>): Observable<State>
        • Parameters

          • inputs$: Observable<Inputs>

          Returns Observable<State>

    • inputs: Inputs

      An array of dependencies. When one of the dependencies changes the Observable in init will emit an array of all the dependencies.

    Returns Observable<State>

Generated using TypeDoc