Created
September 20, 2018 02:49
-
-
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
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 { | |
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