Last active
August 28, 2022 21:01
-
-
Save msociety/72996904b21f60c61e67c10360a6c887 to your computer and use it in GitHub Desktop.
André Staltz (@andrestaltz): 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
/* | |
* André Staltz (@andrestaltz): You will learn RxJS at ng-europe 2016 | |
* https://www.youtube.com/watch?v=uQ1zhJHclvs | |
*/ | |
function map(transformFn) { | |
const inputObservable = this; | |
const outputObservable = createObservable(function subscribe(outputObserver) { | |
inputObservable.subscribe({ | |
next: function(x) { | |
const y = transformFn(x); | |
outputObserver.next(y); | |
}, | |
error: e => outputObserver.error(e), | |
complete: () => outputObserver.complete() | |
}); | |
}); | |
return outputObservable; | |
} | |
function filter(conditionFn) { | |
const inputObservable = this; | |
const outputObservable = createObservable(function subscribe(outputObserver) { | |
inputObservable.subscribe({ | |
next: function(x) { | |
const y = conditionFn(x); | |
outputObserver.next(y); | |
}, | |
error: e => outputObserver.error(e), | |
complete: () => outputObserver.complete() | |
}); | |
}); | |
return outputObservable; | |
} | |
function delay(period) { | |
const inputObservable = this; | |
const outputObservable = createObservable(function subscribe(outputObserver) { | |
inputObservable.subscribe({ | |
next: function(x) { | |
setTimeout(() => { | |
outputObserver.next(x); | |
}, period); | |
}, | |
error: e => outputObserver.error(e), | |
complete: () => outputObserver.complete() | |
}); | |
}); | |
return outputObservable; | |
} | |
function createObservable(subscribe) { | |
return { | |
subscribe: subscribe, | |
map: map, | |
filter: filter, | |
delay: delay | |
}; | |
} | |
const arrayObservable = createObservable(function subscribe(ob) { | |
[10, 20, 30].forEach(ob.next); | |
ob.complete(); | |
}); | |
const clickObservable = createObservable(function subscribe(ob) { | |
document.addEventListener("click", ob.next()); | |
}); | |
const observer = { | |
next: function nextCallback(data) { | |
console.log(data); | |
}, | |
error: function errorCallback(data) { | |
console.log(data); | |
}, | |
complete: function completeCallback(data) { | |
console.log("done"); | |
} | |
}; | |
arrayObservable | |
.map(x => x / 10) | |
.filter(x => x !== 2) | |
.subscribe(observer); | |
clickObservable | |
.map(ev => ev.clientX) | |
.filter(x => x > 200) | |
.delay(2000) | |
.subscribe(observer); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment