Skip to content
On this page

useObservable

Category
Package
@vueuse/rxjs
Last Changed
3 months ago

Use an Observable, return a ref and automatically unsubscribe from it when the component is unmounted. available in add-on @vueuse/rxjs

Usage

import { ref } from 'vue'
import { useObservable } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { mapTo, startWith, scan } from 'rxjs/operators'

// setup()
const count = useObservable(
  interval(1000).pipe(
    mapTo(1),
    startWith(0),
    scan((total, next) => next + total),
  )
)
import { ref } from 'vue'
import { useObservable } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { mapTo, startWith, scan } from 'rxjs/operators'

// setup()
const count = useObservable(
  interval(1000).pipe(
    mapTo(1),
    startWith(0),
    scan((total, next) => next + total),
  )
)

If you want to add custom error handling to an observable that might error, you can supply an optional onError configuration. Without this, RxJS will treat any error in the supplied observable as an "unhandled error" and it will be thrown in a new call stack and reported to window.onerror (or process.on('error') if you happen to be in node).

import { ref } from 'vue'
import { useObservable } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map } from 'rxjs/operators'

// setup()
const count = useObservable(
  interval(1000).pipe(
    map(n => {
      if (n === 10) {
        throw new Error('oops')
      }
      return n + n
    })
  ),
  {
    onError: err => {
      console.log(err.message) // "oops"
    }
  }
)
import { ref } from 'vue'
import { useObservable } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map } from 'rxjs/operators'

// setup()
const count = useObservable(
  interval(1000).pipe(
    map(n => {
      if (n === 10) {
        throw new Error('oops')
      }
      return n + n
    })
  ),
  {
    onError: err => {
      console.log(err.message) // "oops"
    }
  }
)

Type Declarations

export interface UseObservableOptions {
  onError?: (err: any) => void
}
export declare function useObservable<H>(
  observable: Observable<H>,
  options?: UseObservableOptions
): Readonly<Ref<H>>
export interface UseObservableOptions {
  onError?: (err: any) => void
}
export declare function useObservable<H>(
  observable: Observable<H>,
  options?: UseObservableOptions
): Readonly<Ref<H>>

Source

SourceDocs

Contributors

Anthony Fu
Ben Lesh
Michel Betancourt

Changelog

v6.0.0-beta.2 on 8/9/2021
ff21b - feat: use tryOnScopeDispose instead of tryOnUnmounted
v5.0.2 on 6/9/2021
807a8 - feat: now supports optional error handling via onError. (#567)
useObservable has loaded