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!),
);
},
),
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With