跳到主要内容

useObservable

分类
导出大小
225 B
@vueuse/rxjs
上次更改
8 个月前

使用 RxJS Observable,返回一个 ref,并在组件卸载时自动取消订阅。可在 @vueuse/rxjs 附加组件中使用。

用法

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),
  ),
)

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

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

类型声明

ts
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
>>

来源

源码文档

贡献者

Anthony Fu
Anthony Fu
SerKo
Robin
IlyaL
Curt Grimes
Vincent Schramer
Ben Lesh
Michel Betancourt

更新日志

0a9ed - feat!: 放弃对 Vue 2 的支持,优化打包并清理 (#4349)

根据 MIT 许可证发布。