RxJS - studiofu/brain GitHub Wiki
Quick Start
Traditional JQuery
$(function() {
var startTime;
$('#hold-me').mousedown(function() {
startTime = new Date();
})
$('#hold-me').mouseup(function() {
if (startTime) {
const elapsedMilliseconds = (new Date() - startTime);
startTime = null;
$('#hold-time').text(elapsedMilliseconds);
$.ajax('https://timing-sense-score-board.herokuapp.com/score/' + elapsedMilliseconds).done((res) => {
$('#rank').text('你超過了' + res.rank + '% 的用戶');
});
}
})
})
ES6 To ES5 - Babel
npx babel-node src/index.js
Map Sample
import {of} from 'rxjs/observable/of';
import {map} from'rxjs/operators';
const source$ = of(1,2,3);
const result$ = source$.pipe(
map(x => x*2)
);
result$.subscribe(console.log);
First
// RxJS v6+
import { from } from 'rxjs';
import { first } from 'rxjs/operators';
const source = from([1, 2, 3, 4, 5]);
//no arguments, emit first value
const example = source.pipe(first());
//output: "First value: 1"
const subscribe = example.subscribe(val => console.log(`First value: ${val}`));
Subject
Subject could be a data producer and data consumer
it could subscribe observable data stream (upstream)
it could be subscribed by other object (downstream)
const a = subject.subscribe(v => console.log('a:'+v)); // being subscribed
const b = subject.subscribe(v => console.log('b:'+v));
source$ = Observable.of([1,2,3,4,5]);
source$.subscribe(a); // subscribe the source$
source$.subscribe(b);
Resources
Inroduction to Reactive Programming
https://gist.github.com/staltz/868e7e9bc2a7b8c1f754
Simple Tutorial
https://www.devglan.com/javascript/rxjs-tutorial
Ajax - getJSON, done, each, fail and alawys
深入淺出 RxJS
https://github.com/mocheng/dissecting-rxjs
Learn RxJS
Subject vs Observable
https://javascript.tutorialhorizon.com/2017/03/23/rxjs-subject-vs-observable/
Introduction to Subject
https://ithelp.ithome.com.tw/articles/10188677
RxJS Reduce - Scan