Skip to content

useObservable

使用 RxJS Observable,返回 ref,并在组件卸载时自动取消订阅。

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

用法

¥Usage

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

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

如果你想要向可能出错的 Observable 添加自定义错误处理,你可以提供可选的 onError 配置。如果没有这个,RxJS 会将所提供的 Observable 中的任何错误视为 "未处理的错误",并将其扔到新的调用堆栈中并报告给 window.onerror(如果碰巧在 Node 中,则报告给 process.on('error'))。

¥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).

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

// 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"
    },
  },
)
js
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"
    },
  },
)

类型声明

typescript
export interface UseObservableOptions<I> {
  onError?: (err: any) => void
  /**
   * The value that should be set if the observable has not emitted.
   */
  initialValue?: I | undefined
}
export declare function useObservable<H, I = undefined>(
  observable: Observable<H>,
  options?: UseObservableOptions<I | undefined>,
): Readonly<Ref<H | I>>

源代码

源代码文档

变更日志

No recent changes

VueUse 中文网 - 粤ICP备13048890号