Skip to content

Instantly share code, notes, and snippets.

@jemmyw
Created May 6, 2019 21:26
Show Gist options
  • Save jemmyw/04e3579f5c2b510d240face59848c4da to your computer and use it in GitHub Desktop.
Save jemmyw/04e3579f5c2b510d240face59848c4da to your computer and use it in GitHub Desktop.
useSubscription
import { useEffect, useState } from 'react';
import { Observable, Subscription } from 'rxjs';
export const useSubscription = (fn: () => Subscription, inputs: any[]) => {
return useEffect(() => {
const subscription = fn();
return () => subscription.unsubscribe();
}, inputs);
};
export const useSubscriptionState = <T>(
fn: () => Observable<T>,
inputs: any[]
): [T | null, boolean] => {
const [state, setState] = useState<T | null>(null);
const [loading, setLoading] = useState(true);
useSubscription(
() =>
fn().subscribe(n => {
setState(n);
setLoading(false);
}),
inputs
);
return [state, loading];
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment