Last active
September 18, 2019 17:39
-
-
Save ddoronin/cb5fa9445d003dcc931beabfbe2eed5c to your computer and use it in GitHub Desktop.
useRx and useRxTap React Hooks for RxJS
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from "react"; | |
import { Observable, Subscription } from "rxjs"; | |
import { tap } from 'rxjs/operators'; | |
/** | |
* Reactive Hook that returns a tuple of resolved value and error. | |
* @param { Observable<T> } observable$ | |
* @param { T } defaultValue | |
*/ | |
export function useRx<T>( | |
observable$: Observable<T>, | |
defaultValue: T | (() => T) | |
): [T, any?] { | |
const [x, setX] = useState(defaultValue); | |
const [error, setError] = useState(); | |
let subscription: Subscription; | |
useEffect(() => { | |
if (!subscription) { | |
subscription = observable$.subscribe(setX, setError); | |
} | |
return () => subscription.unsubscribe(); | |
}, [observable$]); | |
return [x, error]; | |
} | |
/** | |
* Reactive Hook that triggers callbacks on observable updates. | |
* @param { Observable<T> } observable$ | |
* @param { T } defaultValue | |
*/ | |
export function useRxTap<T>( | |
observable$: Observable<T>, | |
next?: (x: T) => void, | |
error?: (e: any) => void, | |
complete?: () => void | |
): void { | |
let subscription: Subscription; | |
useEffect(() => { | |
if (!subscription) { | |
subscription = observable$.pipe(tap(next, error, complete)).subscribe(); | |
} | |
return () => subscription.unsubscribe(); | |
}, [observable$]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment