rx.js 的冷和热观察

http://cn.rx.js.org/manual/overview.html#h213

https://rxjs-cn.github.io/rxjs5-ultimate-cn/content/hot-n-cold-observables.html

冷观察

const {
  Observable
} = require('rxjs');

var clock = Observable
.interval(1000)
.take(5)
.map(x => x+1)

setTimeout(() => {
  clock.subscribe(x => console.log(`     b: ${x}`))
}, 4500);

clock.subscribe(x => console.log(`a: ${x}`));

// 
>node test/test.js
a: 1
a: 2
a: 3
a: 4
a: 5
     b: 1
     b: 2
     b: 3
     b: 4
     b: 5

热观察

const {
  Observable
} = require('rxjs');

var clock = Observable
.interval(1000)
.take(5)
.map(x => x+1)
.publish()
.refCount()

setTimeout(() => {
  clock.subscribe(x => console.log(`     b: ${x}`))
}, 4500);

clock.subscribe(x => console.log(`a: ${x}`));

// 
>node test/test.js
a: 1
a: 2
a: 3
a: 4
a: 5
     b: 5

共享(热)

const { interval, of, merge, concat } = require('rxjs');
const {share, take} = require('rxjs/operators');

let x$ = interval(500).pipe( take(5), share() )

x$.subscribe(v => console.log(`A$ => ${v}`))

setTimeout(()=>{
  x$.subscribe(v => console.log(`    B$ => ${v}`))
}, 2000)

λ node main.js
A$ => 0
A$ => 1
A$ => 2
A$ => 3
    B$ => 3
A$ => 4
    B$ => 4
posted @ 2018-04-12 16:43  Ajanuw  阅读(363)  评论(0编辑  收藏  举报