rxdart

How to set backpressure on dart stream. (or rxDart)


Is there a way to set backpressure on a dart stream?

I want to implement a function like this:

  1. The user presses a button.
  2. Add data to PublishSubject.
  3. Even if other data is added while the added data is being processed, it is ignored.

I don't know how to this it.

Any good way?


Solution

  • Dart Stream has built-in backpressure (buffered).

    Stream.periodic(const Duration(milliseconds: 100), (i) => i)
      .take(5)
      .listen((v) async {
        await Future<void>.delayed(const Duration(milliseconds: 500));
        print(v);
      });
    
    await Future<void>.delayed(const Duration(seconds: 10));
    
    // will print 0, 1, 2, 3, 4
    

    You can use exhaustMap of rxdart to ignore/drop values.

    
    Stream.periodic(const Duration(milliseconds: 100), (i) => i)
      .take(5)
      .exhaustMap((v) => Rx.timer(v, const Duration(milliseconds: 500)))
      .listen(print);
    
    await Future<void>.delayed(const Duration(seconds: 10));
    
    // will print 0