watchExtractedObservable

watchExtractedObservable

RxJS の Observable の値を、1つ以上のコンポーザブルから抽出して監視します。

Observable が変更されたときに自動的に購読を解除し、コンポーネントがアンマウントされたときにも自動的に購読を解除します。

watch のすべてのオーバーロードをサポートします。

使用法

import { watchExtractedObservable } from '@vueuse/rxjs'
import { computed, reactive, shallowRef } from 'vue'
import { AudioPlayer } from '../my/libs/AudioPlayer'

// setup()

const audio = shallowRef<HTMLAudioElement>()
const player = computed(() => (audio.value ? new AudioPlayer(audio) : null))
const state = reactive({
  progress: 0,
})

watchExtractedObservable(player, p => p.progress$, (percentage) => {
  state.progress = percentage * 100
})

エラーを起こす可能性のある Observable にカスタムエラーハンドリングを追加したい場合は、オプションの onError 設定を提供できます。これがない場合、RxJS は提供された Observable のエラーを「未処理のエラー」として扱い、新しいコールスタックでスローされ、window.onerror(または Node の場合は process.on('error'))に報告されます。

監視している Observable が完了したときに特別な動作を付けたい場合は、オプションの onComplete 設定を提供することもできます。

import { watchExtractedObservable } from '@vueuse/rxjs'
import { computed, reactive, shallowRef } from 'vue'
import { AudioPlayer } from '../my/libs/AudioPlayer'

// setup()

const audio = shallowRef<HTMLAudioElement>()
const player = computed(() => (audio.value ? new AudioPlayer(audio) : null))
const state = reactive({
  progress: 0,
})

watchExtractedObservable(player, p => p.progress$, (percentage) => {
  state.progress = percentage * 100
}, {
  onError: (err: unknown) => {
    console.error(err)
  },
  onComplete: () => {
    state.progress = 100 // または 0、またはその他
  },
})

必要に応じて、最後の引数として watch オプションを渡すこともできます:

import { watchExtractedObservable } from '@vueuse/rxjs'
import { computed, reactive, shallowRef } from 'vue'
import { AudioPlayer } from '../my/libs/AudioPlayer'

// setup()

const audio = shallowRef<HTMLAudioElement>()
const player = computed(() => (audio.value ? new AudioPlayer(audio) : null))
const state = reactive({
  progress: 0,
})

watchExtractedObservable(player, p => p.progress$, (percentage) => {
  state.progress = percentage * 100
}, {
  onError: (err: unknown) => {
    console.error(err)
  }
}, {
  immediate: true
})