2017-05-16 80 views
1

從rxjs網站油門例如,如何獲得rxjs中的限制值?

所發射的序列是0 4 2 1 3

輸出序列是0 1.(由於4,2和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'); 
    }); 

控制檯將輸出

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. 刪除受限索引。

你可以在另一種情況下使用這種技術。

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