Skip to content

Instantly share code, notes, and snippets.

@JSila
Last active January 28, 2017 13:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JSila/40213dab4b96e335a5d43d3f4c5ca1f4 to your computer and use it in GitHub Desktop.
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
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