Skip to content
This repository has been archived by the owner on Nov 26, 2018. It is now read-only.

Commit

Permalink
fix(withObs): share props$
Browse files Browse the repository at this point in the history
  • Loading branch information
gregberge committed Apr 25, 2017
1 parent acec5a7 commit 37c9533
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 1 deletion.
21 changes: 21 additions & 0 deletions src/__tests__/withObs.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,27 @@ describe('withObs', () => {
expect(wrapper.find('div').prop('className')).toBe('foo')
})

it('should share props$', () => {
let count = 0

const Component = compose(
withObs(() => ({
props$: Rx.Observable.create((observer) => {
count += 1
observer.next({})
}),
})),
withObs(({ props$ }) => {
props$.subscribe()
props$.subscribe()
return { props$ }
}),
)('div')

mount(<Component />)
expect(count).toBe(1)
})

it('should be merged with other hoc', () => {
const Component = compose(
withObs(() => ({})),
Expand Down
36 changes: 36 additions & 0 deletions src/utils/shareObservable.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
/* eslint-disable import/prefer-default-export */
import createObservable from './createObservable'

const shareObservable = (observable) => {
const observers = []
let emitted
let lastValue

observable.subscribe({
next: (value) => {
emitted = true
lastValue = value
observers.forEach(o => o.next(value))
},
complete: value => observers.forEach(o => o.complete(value)),
error: error => observers.forEach(o => o.error(error)),
})

return createObservable((observer) => {
observers.push(observer)

if (emitted) {
observers.forEach(o => o.next(lastValue))
}

return {
unsubscribe: () => {
const index = observers.indexOf(observer)
if (index === -1) return
observers.splice(index, 1)
},
}
})
}

export default shareObservable
4 changes: 3 additions & 1 deletion src/withObs.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import callOrUse from './utils/callOrUse'
import createHOCFromMapper from './utils/createHOCFromMapper'
import shareObservable from './utils/shareObservable'
import createHelper from './createHelper'

/**
Expand All @@ -20,7 +21,8 @@ import createHelper from './createHelper'
* }))
*/
const withObs = obsMapper => createHOCFromMapper((props$, obs) => {
const nextObs = callOrUse(obsMapper, { ...obs, props$ })
const sharedProps$ = shareObservable(props$)
const nextObs = callOrUse(obsMapper, { ...obs, props$: sharedProps$ })
const { props$: nextProps$ = props$ } = nextObs
delete nextObs.props$
return [nextProps$, { ...obs, ...nextObs }]
Expand Down

0 comments on commit 37c9533

Please sign in to comment.