[RxJS] Combining Streams with CombineLatest
2016-03-11 04:17
459 查看
Two streams often need to work together to produce the values you’ll need. This lesson shows how to use an input stream and an interval stream together and push an object with both values through the stream.
They last param of combineLatest is a result function, which can parse the result in the fucntion:
const Observable = Rx.Observable; const startButton = document.querySelector('#start'); const halfButton = document.querySelector('#half'); const quarterButton = document.querySelector('#quarter'); const input = document.querySelector("#input"); const stopButton = document.querySelector('#stop'); const resetButton = document.querySelector('#reset'); const data = {count:0}; const inc = (acc)=> ({count: acc.count + 1}); const reset = (acc)=> data; const start$ = Observable.fromEvent(startButton, 'click'); const half$ = Observable.fromEvent(halfButton, 'click'); const quarter$ = Observable.fromEvent(quarterButton, 'click'); const stop$ = Observable.fromEvent(stopButton, 'click'); const reset$ = Observable.fromEvent(resetButton, 'click'); const starters$ = Observable.merge( start$.mapTo(1000), half$.mapTo(500), quarter$.mapTo(250) ); const intervalActions = (time) => { return Observable.merge( Observable.interval(time) .takeUntil(stop$) .mapTo(inc), reset$.mapTo(reset) ) }; const timer$ = starters$ .switchMap(intervalActions) .startWith(data) .scan( (acc, curr) => curr(acc)); const input$ = Observable.fromEvent(input, "input") .map(ev=>ev.target.value); Observable.combineLatest( timer$, input$ ) // We will get an array combineLatest .map((array)=>{ return {count: array[0].count, input: array[1]} }) .subscribe(x => console.log(x))
They last param of combineLatest is a result function, which can parse the result in the fucntion:
Observable.combineLatest( timer$, input$, (timer, input)=>{ return {count: timer.count, input} } ) .subscribe(x => console.log(x))
相关文章推荐
- [RxJS] Getting Input Text with Map
- [RxJS] Refactoring Composable Streams in RxJS, switchMap()
- JavaScript学习笔记(九)—— JS 理解闭包
- 通过寄生组合式继承创建js的异常类
- json树递归js查询json父子节点
- [RxJS] Handling Multiple Streams with Merge
- JavaScript高级程序设计(第三版)学习笔记1~5章
- JavaScript高级程序设计(第三版)学习笔记6、7章
- JavaScript获取客户端IP的方法(新方法)
- js仿百度登录页实现拖动窗口效果
- javascript html5 canvas实现可拖动省份的中国地图
- JavaScript获取图片像素颜色并转换为box-shadow显示
- JavaScript中setTimeout和setInterval函数的传参及调用
- 举例说明JavaScript中的实例对象与原型对象
- JavaScript操作HTML DOM节点的基础教程
- fastjson序列化原理详解
- JavaScript闭包
- fastjson1.2.8原理
- myjs
- 面向对象编程-js