Skip to content

Instantly share code, notes, and snippets.

@zmnv
Last active October 13, 2018 07:00
Show Gist options
  • Save zmnv/7a6e5b113776a8da0aab2f48cd8fc8ef to your computer and use it in GitHub Desktop.
Save zmnv/7a6e5b113776a8da0aab2f48cd8fc8ef to your computer and use it in GitHub Desktop.
Что такое Observable. Примитивная реализация. https://www.youtube.com/watch?v=NK-WzH3RBds
'use strict';
/* Исходная задача */
for (let letter of 'Hello, world!') {
console.log(letter);
}
/* Добавляем гибкости */
function observe(observable) {
for (let letter of observable) {
console.log(letter);
}
}
observe('Hello World!');
/* Добавляем наблюдение */
function observe(observable, next, done) {
for (let letter of observable) {
next(letter);
}
done();
}
observe('Hello World!', letter => console.log(letter), () => console.log('Done!'));
'use strict';
/* Исходная задача */
for (let letter of 'Hello, world!') {
console.log(letter);
}
/* Продвинутая гибкость */
class Observable {
constructor(source) {
this.source = source;
this.result = this.source;
}
subscribe(next) {
for (let item of this.result) {
next(letter)
}
}
}
new Observable('Hello world!').subscribe(letter => console.log(letter));
/* Простая реализация Observable. Больше возможностей. */
class Observable {
constructor(source) {
this.source = source.split(''); // превращаем в массив для filter
this.result = this.source;
}
subscribe(next) {
for (let item of this.result) {
next(letter)
}
}
filter(predicate) {
this.result = this.result.filter(predicate);
return this;
}
map(callback) {
this.result = this.result.map(callback);
return this;
}
}
new Observable('Hello world!')
.map(letter => letter.toUpperCase())
.filter(letter => letter === 'H')
.subscribe(letter => console.log(letter));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment