Skip to content

Instantly share code, notes, and snippets.

@allenfantasy allenfantasy/basic.js
Last active Jan 29, 2018

Embed
What would you like to do?
Observable learning snippets. Inspired and referenced from "30天精通RxJS": https://ithelp.ithome.com.tw/articles/10187005
//=== Using Observable.create() ===//
import Rx from 'rxjs/Rx'
let observable = Rx.Observable
.create(observer => {
observer.next('Jerry')
observer.next('Anna')
})
// OR:
// let observable = Rx.Observable.of('Jerry', 'Anna')
// let observable = Rx.Observable.from(['Jerry', 'Anna']) // **any enumerables**
observable.subscribe(value => console.log(value))
//=== a standard Observer ===//
let ob2 = Rx.Observable
.create(observer => {
observer.next('Jerry')
observer.next('Anna')
observer.complete()
observer.next('not work')
})
let observer2 = {
next (value) {
console.log(value)
},
error (err) {
console.log(err)
},
complete () {
console.log('complete')
}
}
ob2.subscribe(observer2)
// Expectation:
// Jerry
// Anna
// complete
//===
// A simple generator which would be use to iterate a string input and extract all numbers.
function* getNumbers(words) {
for (let word of words) {
if (/^[0-9]+$/.test(word)) {
yield parseInt(word, 10);
}
}
}
const iterator = getNumbers('30 天精通 RxJS (04)');
iterator.next();
// { value: 3, done: false }
iterator.next();
// { value: 0, done: false }
iterator.next();
// { value: 0, done: false }
iterator.next();
// { value: 4, done: false }
iterator.next();
// { value: undefined, done: true }
// A simpliest iterator
let arr = [1,2,3]
let iterator = arr[Symbol.iterator]()
iterator.next()
// { value: 1, done: false }
iterator.next()
// { value: 2, done: false }
iterator.next()
// { value: 3, done: false }
iterator.next()
// { value: undefined, done: true }
// Producer is a very naive implementation of EventEmitter without event name.
class Producer {
constructor () {
this.listeners = []
}
addListener (listener) {
if (typeof listener === 'function') {
this.listeners.push(listener)
} else {
throw new Error('listener 必须是 function')
}
}
removeListener (listener) {
this.listeners.splice(this.listeners.indexOf(listener), 1)
}
emit (message) {
this.listeners.forEach(listener => {
listener(message)
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.