2013-02-25 51 views

回答

3

現在還沒有這樣的流式方法。一個增強請求已被提交,您可以登錄issue 8492

但是,您可以使用where方法來做到這一點。在下面爲例,我已經定義了一個ThrottleFilter類忽略定持續時間期間的活動:

import 'dart:async'; 

class ThrottleFilter<T> { 
    DateTime lastEventDateTime = null; 
    final Duration duration; 

    ThrottleFilter(this.duration); 

    bool call(T e) { 
    final now = new DateTime.now(); 
    if (lastEventDateTime == null || 
     now.difference(lastEventDateTime) > duration) { 
     lastEventDateTime = now; 
     return true; 
    } 
    return false; 
    } 
} 

main() { 
    final sc = new StreamController<int>(); 
    final stream = sc.stream; 

    // filter stream with ThrottleFilter 
    stream.where(new ThrottleFilter<int>(const Duration(seconds: 10)).call) 
    .listen(print); 

    // send ints to stream every second, but ThrottleFilter will give only one int 
    // every 10 sec. 
    int i = 0; 
    new Timer.repeating(const Duration(seconds:1), (t) { sc.add(i++); }); 
} 
1

以下版本更接近於什麼Observable.Throttle做:

class Throttle extends StreamEventTransformer { 
    final duration; 
    Timer lastTimer; 

    Throttle(millis) : 
    duration = new Duration(milliseconds : millis); 


    void handleData(event, EventSink<int> sink) { 
    if(lastTimer != null){ 
     lastTimer.cancel(); 
    } 
    lastTimer = new Timer(duration,() => sink.add(event)); 
    } 
} 

main(){ 
    //... 
    stream.transform(new Throttle(500)).listen((_) => print(_)); 
    //.. 
}