Last active
August 29, 2015 14:07
-
-
Save mattpodwysocki/aec873dddcfa0e0c4835 to your computer and use it in GitHub Desktop.
Event Composition using events to control logic.
This file contains 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
#!/usr/bin/env node-forward | |
var Rx = require('rx'), | |
EventEmitter = require('events').EventEmitter, | |
fromEvent = Rx.Observable.fromEvent; | |
function throwError(err) { | |
return Rx.Observable.throw(err); | |
} | |
// Could be any data source | |
var e = new EventEmitter(); | |
var connectEvent = fromEvent(e, 'connect'), | |
dataEvent = fromEvent(e, 'data'), | |
errorEvent = fromEvent(e, 'error'), | |
endEvent = fromEvent(e, 'end'); | |
// Cross the streams! | |
// Note that if an error or end happens, we terminate and clean up handlers! | |
var stream = dataEvent | |
.merge(errorEvent.flatMap(throwError)) | |
.skipUntil(connectEvent.amb(errorEvent)) | |
.takeUntil(endEvent.amb(errorEvent)); | |
// Start you a processing | |
var subscription = stream.subscribe( | |
function (data) { | |
// Do something with the data | |
}, | |
function (err) { | |
// Tell the world we've got a problem | |
}, | |
function () { | |
// Tell the world we're done | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment