Skip to content

toObserver

Category
Export Size
73 B
Package
@vueuse/rxjs
Last Changed
3 hours ago

ref 转换为 RxJS Observer 的语法糖函数。 Available in the @vueuse/rxjs add-on.

用法

ts
import { from, fromEvent, toObserver, useSubscription } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import { map, mapTo, startWith, takeUntil, withLatestFrom } from 'rxjs/operators'
import { shallowRef } from 'vue'

const count = shallowRef(0)
const button = shallowRef<HTMLButtonElement | null>(null)

useSubscription(
  interval(1000)
    .pipe(
      mapTo(1),
      takeUntil(fromEvent(button, 'click')),
      withLatestFrom(from(count).pipe(startWith(0))),
      map(([curr, total]) => curr + total),
    )
    .subscribe(toObserver(count)), // 等同于 ).subscribe(val => (count.value = val))
)
js
import { from, fromEvent, toObserver, useSubscription } from '@vueuse/rxjs'
import { interval } from 'rxjs'
import {
  map,
  mapTo,
  startWith,
  takeUntil,
  withLatestFrom,
} from 'rxjs/operators'
import { shallowRef } from 'vue'
const count = shallowRef(0)
const button = shallowRef(null)
useSubscription(
  interval(1000)
    .pipe(
      mapTo(1),
      takeUntil(fromEvent(button, 'click')),
      withLatestFrom(from(count).pipe(startWith(0))),
      map(([curr, total]) => curr + total),
    )
    .subscribe(toObserver(count)),
)

Type Declarations

typescript
export declare function toObserver<T>(value: Ref<T>): NextObserver<T>

Source

SourceDocs

Contributors

jorshen

Changelog

No recent changes

Released under the MIT License.