2017-05-16 8 views
1

,rxjs에서 스로틀 값을 얻는 방법은 무엇입니까? rxjs 사이트 스로틀 예의

방출 된 시퀀스는 0 4 2 1 3

출력 시퀀스는 0 1

var Rx = require('rxjs/Rx'); 
var times = [ 
    { value: 0, time: 100 }, 
    { value: 1, time: 600 }, 
    { value: 2, time: 400 }, 
    { value: 3, time: 900 }, 
    { value: 4, time: 200 } 
]; 

// Delay each item by time and project value; 
var source = Rx.Observable.from(times) 
    .flatMap(function (item) { 
    return Rx.Observable 
     .of(item.value) 
     .delay(item.time); 
    }) 
    .throttleTime(300 /* ms */); 

var subscription = source.subscribe(
    function (x) { 
    console.log('Next: %s', x); 
    }, 
    function (err) { 
    console.log('Error: %s', err); 
    }, 
    function() { 
    console.log('Completed'); 
    }); 

(1, 2, 4가 삭제 되었기 때문에) 콘솔에서 출력됩니다

Next: 0 (at 100ms) // The value 4 was dropped(at 200ms) 
        // The value 2 was dropped(at 400ms) 
Next: 1 (at 600ms) 
        // The value 3 was dropped(at 900ms) 
Completed 

하지만 드롭 된 값 스트림을 가져올 수 있습니까?

Next: 4 (at 200ms) 
Next: 2 (at 400ms) 
Next: 3 (at 900ms) 
Completed 
+1

정확히 무엇을 원하십니까? 왜 처음 4? 1? 여기에 어떤 논리도 보이지 않습니다. – Maxime

+0

값 4는 200ms에 방출됩니다. 값 1은 600ms에 방출됩니다. 따라서 값 4는 먼저 1보다 작습니다. –

+0

내 몸 상태가 좋지 않습니다. 시간은 단지 증가합니다 ... :) – Maxime

답변

1
  1. 소스에 인덱스를 연결합니다.
  2. 소스의 최신 색인 값을 결합하여 제한했습니다.
  3. 소스와 조절 된 색인을 비교합니다. 소스 인덱스> 스로틀 링 된 인덱스 인 경우 소스가 스로틀되지 않습니다.
  4. 색인 제거 색인을 제거하십시오.

이 기술은 다른 NOT 경우에 사용할 수 있습니다.

var Rx = require('rxjs/Rx'); 
var times = [ 
    { value: 0, time: 100 }, 
    { value: 1, time: 600 }, 
    { value: 2, time: 400 }, 
    { value: 3, time: 900 }, 
    { value: 4, time: 200 } 
]; 

// Delay each item by time and project value; 
var source = Rx.Observable.from(times) 
    .mergeMap(function (item) { 
     return Rx.Observable 
      .of(item.value) 
      .delay(item.time); 
    }); 

var indexedSource = source 
    .scan((_, value, index) => { 
     // console.log(`value = ${value}, index = ${index}`) 
     return [value, index]; 
    }, undefined) 
    .share(); 

var indexedThrottled = indexedSource 
    .throttleTime(300 /* ms */); 

var throttled = indexedThrottled 
    .map(value => value[0]); 

var notThrottled = Rx.Observable.combineLatest(indexedThrottled, indexedSource) 
    .filter(combined => { 
     var filteredIndex = combined[0][1]; 
     var sourceIndex = combined[1][1]; 

     return sourceIndex > filteredIndex ? true : false; 
    }) 
    .map(combined => { 
     return combined[1][0]; 
    }); 

source.subscribe(value => console.log(`source : ${value}`)); 
throttled.subscribe(value => console.log(`++++++ : ${value}`)); 
notThrottled.subscribe(value => console.log(`------ : ${value}`)); 
+0

combineLatest에 대한 인수의 순서는 매우 중요합니다. – thatseeyou