Skip to content

Conversation

@tom-sherman
Copy link

@tom-sherman tom-sherman commented Oct 25, 2019

Opening mainly to see if this is a good idea or now! Happy to clean up the API/examples if it is.

Basically I needed a way to restart the observable on dependency changes. I've added another argument to userObservable which allows you to set the dependencies of useEffect. Let me know what you think!

import React from 'react' import ReactDOM from 'react-dom' import { useObservable } from 'rxjs-hooks' import { from } from 'rxjs' import { map, take } from 'rxjs/operators' function App(props: { foo: number }) { const value = useObservable(() => from([1, 2, 3, 4]).pipe( map(val => val + props.foo) ), 200, [props.foo]) return ( // render four times // 2, 4, 5, 6 <h1>{value}</h1> ) } ReactDOM.render(<App foo={1} />, document.querySelector('#app')) ReactDOM.render(<App foo={2} />, document.querySelector('#app'))
@tom-sherman tom-sherman changed the title Refresh ovbservable on dependency change Refresh observable on dependency change Oct 25, 2019
@Brooooooklyn
Copy link
Contributor

The behavior in you implmentation is switchMap when every deps changed. That may not expected behavior in some scenarios.
If you want refresh aka switchMap your Observable, you could write codes like that:

const value = useObservable((deps$) => deps$.pipe( switchMap(foo => from([1, 2, 3]).pipe( map(val => val + foo) )), ) , 200, [props.foo])

And also, you can choose exhaustMap or concatMap or flatMap it

@tom-sherman tom-sherman closed this Nov 9, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

2 participants