Skip to content

Commit

Permalink
fix: Apply timer debounce to avoid bombardment of request within 1 se…
Browse files Browse the repository at this point in the history
…cond #2647
  • Loading branch information
bibash28 committed Jun 19, 2024
1 parent e5d1ec9 commit b9f2fef
Showing 1 changed file with 52 additions and 36 deletions.
88 changes: 52 additions & 36 deletions lib/connection_bridge/beacon/cubit/beacon_cubit.dart
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import 'dart:async';
import 'dart:convert';

import 'package:altme/app/app.dart';
Expand Down Expand Up @@ -31,57 +32,72 @@ class BeaconCubit extends Cubit<BeaconState> {
}
}

Timer? debounce;

void listenToBeacon() {
try {
log.i('listening to beacon');

beacon.getBeaconResponse().listen(
(data) {
(data) async {
final Map<String, dynamic> requestJson =
jsonDecode(data) as Map<String, dynamic>;
final BeaconRequest beaconRequest =
BeaconRequest.fromJson(requestJson);

log.i('beacon response - $requestJson');
log.i('beaconRequest.type - ${beaconRequest.type}');
switch (beaconRequest.type) {
case RequestType.permission:
emit(
state.copyWith(
status: BeaconStatus.permission,
beaconRequest: beaconRequest,
),
);

case RequestType.signPayload:
emit(
state.copyWith(
status: BeaconStatus.signPayload,
beaconRequest: beaconRequest,
),
);

case RequestType.operation:
emit(
state.copyWith(
status: BeaconStatus.operation,
beaconRequest: beaconRequest,
),
);

case RequestType.broadcast:
emit(
state.copyWith(
status: BeaconStatus.broadcast,
beaconRequest: beaconRequest,
),
);

// ignore: no_default_cases
default:

/// cancel previous timer if exists
if (debounce?.isActive ?? false) {
log.w('cancelled bombarded request');
debounce!.cancel();
}

debounce = Timer(const Duration(seconds: 1), () {
switch (beaconRequest.type) {
case RequestType.permission:
emit(
state.copyWith(
status: BeaconStatus.permission,
beaconRequest: beaconRequest,
),
);

case RequestType.signPayload:
emit(
state.copyWith(
status: BeaconStatus.signPayload,
beaconRequest: beaconRequest,
),
);

case RequestType.operation:
emit(
state.copyWith(
status: BeaconStatus.operation,
beaconRequest: beaconRequest,
),
);

case RequestType.broadcast:
emit(
state.copyWith(
status: BeaconStatus.broadcast,
beaconRequest: beaconRequest,
),
);

// ignore: no_default_cases
default:
break;
}
debounce!.cancel();
});
},
);
} catch (e) {
debounce!.cancel();
log.e('beacon listening error - $e');
}
}
Expand Down

0 comments on commit b9f2fef

Please sign in to comment.