Loading source
Pulling the file list, source metadata, and syntax-aware rendering for this listing.
Source from repo
Apply VueUse composables in Vue 3/Nuxt projects to replace custom implementations with battle-tested utilities.
Files
Skill
Size
Entrypoint
Format
Open file
Syntax-highlighted preview of this file as included in the skill package.
references/useObservable.md
1---2category: '@RxJS'3---45# useObservable67Use an RxJS [`Observable`](https://rxjs.dev/guide/observable), return a `ref`, and automatically unsubscribe from it when the component is unmounted.89## Usage1011<!-- TODO: import rxjs error if enable twoslash -->1213```ts no-twoslash14import { useObservable } from '@vueuse/rxjs'15import { interval } from 'rxjs'16import { mapTo, scan, startWith } from 'rxjs/operators'1718// setup()19const count = useObservable(20interval(1000).pipe(21mapTo(1),22startWith(0),23scan((total, next) => next + total),24),25)26```2728### Initial Value2930You can provide an initial value that will be used before the Observable emits its first value:3132```ts no-twoslash33import { useObservable } from '@vueuse/rxjs'34import { interval } from 'rxjs'3536const count = useObservable(37interval(1000),38{ initialValue: 0 },39)40// count.value is 0 until the first emission41```4243### Error Handling4445If 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).4647```ts no-twoslash48import { useObservable } from '@vueuse/rxjs'49import { interval } from 'rxjs'50import { map } from 'rxjs/operators'5152// setup()53const count = useObservable(54interval(1000).pipe(55map((n) => {56if (n === 10)57throw new Error('oops')5859return n + n60}),61),62{63onError: (err) => {64console.log(err.message) // "oops"65},66},67)68```6970### Options7172| Option | Type | Description |73| -------------- | -------------------- | ---------------------------------------- |74| `initialValue` | `T` | Value to use before the Observable emits |75| `onError` | `(err: any) => void` | Error handler for Observable errors |7677## Type Declarations7879```ts80export interface UseObservableOptions<I> {81onError?: (err: any) => void82/**83* The value that should be set if the observable has not emitted.84*/85initialValue?: I | undefined86}87export declare function useObservable<H, I = undefined>(88observable: Observable<H>,89options?: UseObservableOptions<I | undefined>,90): Readonly<Ref<H | I>>91```92