Last active
October 13, 2018 07:00
-
-
Save zmnv/7a6e5b113776a8da0aab2f48cd8fc8ef to your computer and use it in GitHub Desktop.
Что такое Observable. Примитивная реализация. https://www.youtube.com/watch?v=NK-WzH3RBds
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
'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!')); | |
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
'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