Last active
January 28, 2017 13:20
-
-
Save JSila/40213dab4b96e335a5d43d3f4c5ca1f4 to your computer and use it in GitHub Desktop.
higher order function for react that auto-unsubscribes from RxJS Observables on componentWillUnmount
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 React, {Component} from 'react' | |
import forEach from 'lodash/forEach' | |
export default () => ComposedComponent => class extends Component { | |
subscriptions = {} | |
componentWillUnmount() { | |
forEach(this.subscriptions, subscription => { | |
subscription.unsubscribe() | |
}) | |
} | |
render() { | |
return <ComposedComponent {...this.props} {...this.state} subscriptions={this.subscriptions} /> | |
} | |
} | |
// note that component will receive object of subscriptions to which you add your subscriptions. e.g. | |
// this.props.subscriptions.click = Rx.Observable.fromEvent(document, 'click') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment