05RxJS高阶Observable

2021-01-05  本文已影响0人  learninginto

高阶的Observale,一个Observalbe还嵌套着其它的Observale

combineAll

高阶转低阶,等到Observable完成后,对收集到的observalbes使用combineLatest

const clicks = fromEvent(document, 'click');
const higherOrder = clicks.pipe(map(ev => interval(1000).pipe(take(2))),
  take(3)
  // 控制数字中有几个流
)
const result = higherOrder.pipe(combineAll())
// combineAll必须要等高阶的流全部完成才能被订阅(点击两次才完成),每次会把点击发出的值用combineLatest策略合并点击的最新值
result.subscribe(x => console.log(x))
concatAll

高阶转低阶,按顺序订阅每一个Observable

const clicks = fromEvent(document, 'click');
const higherOrder = clicks.pipe(map(ev => interval(1000).pipe(take(4))),
)
const result = higherOrder.pipe(concatAll())
result.subscribe(x => console.log(x))

每次点击都转换成只有四个值(0,1,2,3)的定时器

mergeAll

有流就发,没有顺序

const clicks = fromEvent(document, 'click');
const higherOrder = clicks.pipe(map(ev => interval(1000)),
)
const result = higherOrder.pipe(mergeAll())
result.subscribe(x => console.log(x))

每次点击都产生新的流,每个定时器之间的值互不影响。

startWith和endWith
of('from source ').pipe(startWith('first'), endWith('end'))
  .subscribe(x => console.log(x))
//first
//from source 
//end
withLatestFrom

类似combinelatest,不过它只保证第二个流的值是最新的

从点击的事件中取出当前点击位置的横坐标,

const click = fromEvent(document, 'click').pipe(pluck('clientX'))
const interval$ = interval(1000);
const result = click.pipe(withLatestFrom(interval$))
result.subscribe(x => console.log(x))

将click和interval$的位置替换,不管过多久,直到点击之后定时器才被触发

const click = fromEvent(document, 'click').pipe(pluck('clientX'))
const interval$ = interval(1000);
const result = interval$.pipe(withLatestFrom(click))
result.subscribe(x => console.log(x))
上一篇下一篇

猜你喜欢

热点阅读