Last active
August 29, 2015 14:18
-
-
Save bripkens/922e104114c4faf314b5 to your computer and use it in GitHub Desktop.
RxJS
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
var source = Rx.Observable.create(function (observer) { | |
setTimeout(() => observer.onNext(42), 0); | |
setTimeout(() => { | |
observer.onNext(7); | |
observer.onNext(11); | |
observer.onCompleted(); | |
}, 500); | |
// Note that this is optional, you do not have to return this if you require no cleanup | |
return Rx.Disposable.create(() => console.log('disposed')); | |
}); | |
var subscription = source | |
.filter(x => x > 10) | |
.map(x => x * x) | |
.subscribe( | |
x => { | |
console.log('Next: ', x); | |
if (x > 1000) { | |
subscription.dispose(); | |
} | |
}, | |
err => console.error('Error: ', err), | |
() => console.log('Completed') | |
); | |
setTimeout(() => subscription.dispose(), 200); | |
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
// http://jsbin.com/viwizisejo/1/edit?html,js,console | |
var hasOwnProp = {}.hasOwnProperty; | |
function createName (name) { | |
return '$' + name; | |
} | |
function Emitter() { | |
this.subjects = {}; | |
} | |
Emitter.prototype.emit = function (name, data) { | |
var fnName = createName(name); | |
this.subjects[fnName] || (this.subjects[fnName] = new Rx.Subject()); | |
this.subjects[fnName].onNext(data); | |
}; | |
Emitter.prototype.on = function (name) { | |
var fnName = createName(name); | |
this.subjects[fnName] || (this.subjects[fnName] = new Rx.Subject()); | |
return this.subjects[fnName]; | |
}; | |
Emitter.prototype.dispose = function () { | |
var subjects = this.subjects; | |
for (var prop in subjects) { | |
if (hasOwnProp.call(subjects, prop)) { | |
subjects[prop].dispose(); | |
} | |
} | |
this.subjects = {}; | |
}; | |
var emitter = new Emitter(); | |
emitter.on('foo') | |
.filter(function(x) { return x >= 42 }) | |
.forEach(function(a) { | |
console.log('Filtered: ', a); | |
}); | |
var subscription = emitter.on('foo') | |
.forEach(function(a) { | |
console.log('Unfiltered: ', a); | |
}); | |
emitter.emit('foo', 3) | |
emitter.emit('foo', 42) | |
subscription.dispose(); | |
emitter.emit('foo', 43) | |
emitter.emit('foo', 41) | |
console.log('bar'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment