[RxJS] Combining Streams with CombineLatest

Posted Answer1215

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[RxJS] Combining Streams with CombineLatest相关的知识,希望对你有一定的参考价值。

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.

 

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] Combining Streams with CombineLatest的主要内容,如果未能解决你的问题,请参考以下文章

[RxJS] Sharing Streams with Share

[RxJS] Handling Multiple Streams with Merge

[Angular2 Form] Use RxJS Streams with Angular 2 Forms

[Recompose] Merge RxJS Button Event Streams to Build a React Counter Component

[Vue-rx] Access Events from Vue.js Templates as RxJS Streams with domStreams

Node.js Streams 与 Observables