Skip to content

Instantly share code, notes, and snippets.

@Sawtaytoes
Created September 20, 2018 02:49
Show Gist options
  • Save Sawtaytoes/2bf3208409392cc920b4027417a7a6aa to your computer and use it in GitHub Desktop.
Save Sawtaytoes/2bf3208409392cc920b4027417a7a6aa to your computer and use it in GitHub Desktop.
Implementing the observable pattern and solving the real problem of listening for button presses
import {
BUTTON_UP,
doButtonPressAction,
} from './actions'
const createButtonObserver = bluetoothAddress => observer => (
new FlicConnectionChannel(bluetoothAddress)
.on(
'buttonUpOrDown',
buttonPressState => observer.next(buttonPressState)
)
)
const listenForButtonPress = bluetoothAddress => {
const buttonUpDown$ = (
Rx.Observable
.create(
createButtonObserver(bluetoothAddress)
)
)
buttonUpDown$
.buffer(
buttonUpDown$
.debounceTime(300)
)
.map(buttonStates => (
buttonStates[0] === BUTTON_UP
? buttonStates.slice(1)
: buttonStates
))
.filter(buttonPressStates => buttonPressStates.length > 0)
.map(buttonStates => ({
numDown: getNumberOfDowns(buttonStates),
numUp: getNumberOfUps(buttonStates),
}))
.subscribe(
doButtonPressAction(bluetoothAddress)
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment