Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent a Bloc event from being called multiple times within a set period of time

Tags:

flutter

dart

bloc

I'm using a QRCode Scanner which triggers the same Event in my Bloc many times a second

In order to prevent spamming my API

-> I'd like cancel / drop all occurence of this event triggered within 5 seconds after the last one was called


Here is my Bloc event :

    on<SearchWithQRCode>(_onSearchWithQRCode));

& here is for reference the presentation widget triggering the event

        MobileScanner(
          allowDuplicates: true,
          controller: cameraController,
          onDetect: (barcode, args) {
            if (barcode.rawValue == null) return;

            context.read<ScanQrCodeBloc>().add(
                  SearchWithQRUrl(qrUrl: barcode.rawValue!),
                );
          },
        ),

like image 724
Aristidios Avatar asked Dec 19 '25 16:12

Aristidios


1 Answers

In this scenario you might be interested in bloc_concurrency & stream_transform

Using this event transformer :

import 'package:stream_transform/stream_transform.dart';
import 'package:bloc_concurrency/bloc_concurrency.dart';

EventTransformer<E> throttleDroppable<E>(Duration duration) {
  return (events, mapper) {
    return droppable<E>().call(events.throttle(duration), mapper);
  };
}

like so :

  on<SearchWithQRUrl>(
      _onSearchWithQRUrl,
      transformer: throttleDroppable(const Duration(seconds: 5)),
    );

-> All following calls to this event occurring within the set throttle duration (here 5 seconds) will be canceled

like image 157
Aristidios Avatar answered Dec 21 '25 07:12

Aristidios