Skip to content

useWatchExtractedObservable

Category
Export Size
414 B
Package
@reause/rxjs
Last Changed
5 days ago

Watch the values of an RxJS Observable as extracted from one or more hooks.

Automatically unsubscribe on observable change, and automatically unsubscribe from it when the component is unmounted.

Demo

Usage

tsx
import type { 
Observable
} from 'rxjs'
import {
useWatchExtractedObservable
} from '@reause/rxjs'
import {
useState
} from 'react'
import {
Subject
} from 'rxjs'
interface Player {
progress$
:
Observable
<number>
} export function
PlayerProgress
() {
const [
player
] =
useState
<Player>(() => ({
progress$
: new
Subject
<number>() }))
const [
progress
,
setProgress
] =
useState
(0)
const {
stop
} =
useWatchExtractedObservable
(
player
,
p
=>
p
.
progress$
,
setProgress
)
return ( <
div
>
<
p
>{
progress
}</p>
<button onClick={() =>
stop
()}>Stop watching</button>
</div> ) }

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

You can also supply an optional onComplete configuration if you need to attach special behavior when the watched observable completes.

tsx
useWatchExtractedObservable
(player,
p
=>
p
.progress$, setProgress, {
onError
: (
err
: unknown) => {
console
.
error
(
err
)
},
onComplete
: () => {
setProgress(100) // or 0, or whatever }, })

Subscription Options

OptionTypeDescription
onError(err: unknown) => voidError handler for Observable errors
onComplete() => voidCalled when the Observable completes

Return Value

Returns a WatchHandle that can be used to stop watching:

tsx
const { 
stop
} =
useWatchExtractedObservable
(player,
p
=>
p
.progress$, setProgress)
// Later, stop watching
stop
()

Type Declarations

ts
export type OnCleanup = (cleanupFn: () => void) => void

export type WatchExtractedObservableExtractor<Value, E> = (value: NonNullable<Value>, onCleanup: OnCleanup) => Observable<E>

export interface UseWatchExtractedObservableOptions {
    deps?: unknown[];
    onError?: (err: unknown) => void;
    onComplete?: () => void;
}

export interface UseWatchExtractedObservableReturn {
    stop: () => void;
}

export function useWatchExtractedObservable<Value, E>(value: Value | null | undefined, extractor: WatchExtractedObservableExtractor<Value, E>, callback: (snapshot: E) => void, options?: UseWatchExtractedObservableOptions): UseWatchExtractedObservableReturn

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
de6df - fix(rxjs): resolve useWatchExtractedObservable audit findings (#813)
6a703 - feat(rxjs): add useWatchExtractedObservable (#262)

Released under the MIT License. v0.1.8