Skip to content

useObservable

Category
Export Size
212 B
Package
@vueuse/rxjs
Last Changed
last year

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

用法

ts
import { ref } from 'vue'
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),
  ),
)
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 { 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"
    },
  },
)
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>>

Source

SourceDocs

贡献者

Anthony Fu
丶远方
Curt Grimes
Vincent Schramer
Ben Lesh
Michel Betancourt

变更日志

No recent changes

Released under the MIT License.

Build faster with AI
New Masterclass to help you leverage AI in your Vue workflow.
Get Early Access