Skip to content

useObservable

类别
导出体积
212 B
依赖包
@vueuse/rxjs
上次更改
3 minutes ago

使用 RxJS Observable,返回一个 ref,并在组件卸载时自动取消订阅。 Available in the @vueuse/rxjs add-on.

用法

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'))。

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
  /**
   * 如果可观察对象尚未发出,则应设置的值。
   */
  initialValue?: I | undefined
}
export declare function useObservable<H, I = undefined>(
  observable: Observable<H>,
  options?: UseObservableOptions<I | undefined>,
): Readonly<Ref<H | I>>

源码

源码文档

贡献者

Anthony Fu
一纸忘忧
Anthony Fu
Curt Grimes
Vincent Schramer
Ben Lesh
Michel Betancourt

更新日志

没有最近的更新日志