Skip to content

Instantly share code, notes, and snippets.

@pinyin
Created November 26, 2017 01:24
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pinyin/887592ba06e3fc8af168498d04488fd7 to your computer and use it in GitHub Desktop.
Save pinyin/887592ba06e3fc8af168498d04488fd7 to your computer and use it in GitHub Desktop.
import * as React from 'react'
import {Observable} from 'rxjs/Observable'
import {Subject} from 'rxjs/Subject'
import {ISubscription} from 'rxjs/Subscription'
import {Observables} from '../rxjs/Observables'
import {Pipes} from '../rxjs/Pipes'
import {Subjects} from '../rxjs/Subjects'
import {EventHandlers} from '../utils/EventHandler'
export abstract class ReactiveReactComponent<Props, State, Events> extends React.Component<Props, State> {
componentWillMount() {
this._eventSources = Object.keys(this.eventMiddleware)
.map(name => ({
[name]: new Subject()
}))
.reduce((prev, curr) => Object.assign(prev, curr)) as any
this.events = Object.keys(this._eventSources)
.map(name => ({
[name]: (this._eventSources[name] as Subject<any>)
.asObservable()
.let(this.eventMiddleware[name])
}))
.reduce((prev, curr) => Object.assign(prev, curr)) as any
this.trigger = Object.keys(this._eventSources)
.map(name => ({
[name]: (event: any) => {
(this._eventSources[name] as Subject<any>).next(event)
}
}))
.reduce((prev, curr) => Object.assign(prev, curr)) as any
this.setState(this.initialState())
this.subscription = this.sideEffects()
}
componentWillReceiveProps(nextProps: Props) {
if (nextProps != this.props) {
this.subscription.unsubscribe()
this.subscription = this.sideEffects()
}
}
componentWillUnmount(): void {
this.subscription.unsubscribe()
}
abstract render(): JSX.Element
private _eventSources: Subjects<Events>
private subscription: ISubscription
protected abstract sideEffects(): ISubscription
protected abstract initialState(): State
protected abstract eventMiddleware: Pipes<Events>
protected events: Observables<Events>
protected trigger: EventHandlers<Events>
}
export const Pass = <T>(observable: Observable<T>): Observable<T> => observable
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment