Skip to content

useObservable

类别
导出大小
225 B
@vueuse/rxjs
最近修改
2 days ago

使用 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'

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

初始值

🌐 Initial Value

你可以提供一个初始值,该值将在 Observable 发出第一个值之前使用:

🌐 You can provide an initial value that will be used before the Observable emits its first value:

ts
import { useObservable } from '@vueuse/rxjs'
import { interval } from 'rxjs'

const count = useObservable(
  interval(1000),
  { initialValue: 0 },
)
// count.value is 0 until the first emission

错误处理

🌐 Error Handling

如果你想为可能出错的 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'

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

选项

🌐 Options

选项类型描述
initialValueTObservable 发出值之前使用的值
onError(err: any) => voidObservable 错误的错误处理程序