Last active
November 2, 2016 04:58
-
-
Save dfkaye/9c4251a23c8943db417a79394c476747 to your computer and use it in GitHub Desktop.
observable array example by @andrestaltz in "You will learn RxJS at ng-europe 2016"
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
// 1 Nov 2016 | |
// see https://www.youtube.com/watch?v=uQ1zhJHclvs | |
// by @andrestaltz | |
function map(transformFn) { | |
var inputObservable = this; | |
var outputObservable = createObservable(function subscribe(outputObserver) { | |
inputObservable.subscribe({ | |
next: function(x) { | |
var y = transformFn(x) | |
outputObserver.next(y) | |
}, | |
error: function(e) { | |
outputObserver.error(e) | |
}, | |
complete: function () { | |
outputObserver.complete() | |
} | |
}) | |
}) | |
return outputObservable | |
} | |
function filter(conditionFn) { | |
var inputObservable = this; | |
var outputObservable = createObservable(function subscribe(outputObserver) { | |
inputObservable.subscribe({ | |
next: function(x) { | |
if (conditionFn(x)) { | |
outputObserver.next(x) | |
} | |
}, | |
error: function(e) { | |
outputObserver.error(e) | |
}, | |
complete: function () { | |
outputObserver.complete() | |
} | |
}) | |
}) | |
return outputObservable | |
} | |
function createObservable(subscribe) { | |
return { | |
subscribe: subscribe, | |
map: map, | |
filter: filter | |
} | |
} | |
var clickObservable = createObservable(function subscribe(ob) { | |
document.addEventListener('click', ob.next) | |
}) | |
var arrayObservable = createObservable(function subscribe(ob) { | |
['10', 20, 30].map(ob.next) | |
ob.complete() | |
}) | |
var observer = { | |
next: function (data) { | |
console.log(data) | |
}, | |
error: function (err) { | |
console.error(err) | |
}, | |
complete: function () { | |
console.log('done') | |
} | |
} | |
arrayObservable | |
.map(function (x) { | |
return x/10 | |
}) | |
.filter(function (x) { | |
return x !== 2 | |
}) | |
.subscribe(observer) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment