简体   繁体   中英

Throttle stream without buffering

I have some toast messages that I'd like to throttle. I tried using buffer but then I get a bunch of messages in an array when what I'd really like is for the messages to simply stay in the stream until I ask for them. What I ended up doing was zipping my message stream with an interval stream

var messageStream = Rx.Observable.FromEvent(..., 'click');
var intervalStream = Rx.Observable.interval(5000);
messageStream.Zip(intervalStream, (x,_)=>x).subscribe(showToast(x));

Is there a more elegant way to do this?

Have a look at controlled . It enables you to queue values, waiting for you to .request(x) x values. To use with care, as this means memory will be used to buffer the values and memory is not infinite. This could also be a good reading : backpressure

Here's an approach using buffer, followed by a flatMap to unwind the array:

var messageStream = Rx.Observable.FromEvent(..., 'click');
var intervalStream = Rx.Observable.interval(5000);
messageStream
    .buffer(intervalStream)
    .flatMap( function (x) {
        return Rx.Observable.from(x)
    })
    .subscribe( function  (x) { 
        showToast(x) 
    })

Example here on jsfiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM