chatapp3-flutter/lib/shared/tools/sc_heartbeat_utils.dart

70 lines
1.7 KiB
Dart

import 'dart:async';
import 'package:yumi/shared/data_sources/sources/local/user_manager.dart';
import 'package:yumi/shared/data_sources/sources/repositories/sc_user_repository_impl.dart';
import '../../shared/data_sources/models/enum/sc_heartbeat_status.dart';
class SCHeartbeatUtils {
static Timer? _h;
static Timer? _a;
static String _c = SCHeartbeatStatus.ONLINE.name;
static String? _r;
static bool _u = false;
///定时发送心跳
static void scheduleHeartbeat(
String status,
bool upMick, {
String? roomId,
}) async {
cancelTimer();
_c = status;
_u = upMick;
_r = roomId;
if (AccountStorage().getToken().isEmpty) {
return;
}
try {
await SCAccountRepository().heartbeat(_c, _u, roomId: _r);
_h ??= Timer.periodic(Duration(seconds: 60), (timer) {
if (AccountStorage().getToken().isEmpty) {
cancelTimer();
return;
}
SCAccountRepository()
.heartbeat(_c, _u, roomId: _r)
.catchError((_) => {});
});
} catch (e) {
try {
cancelTimer();
} catch (_) {}
}
}
static void cancelTimer() {
_h?.cancel();
_h = null;
_r = null;
cancelAnchorTimer();
}
///上麦主播发送心跳
static void scheduleAnchorHeartbeat(String roomId) async {
cancelAnchorTimer();
scheduleHeartbeat(_c, true, roomId: roomId);
SCAccountRepository().anchorHeartbeat(roomId).whenComplete(() {
_a ??= Timer.periodic(Duration(seconds: 60), (timer) {
SCAccountRepository().anchorHeartbeat(roomId).catchError((_) => {});
});
});
}
static void cancelAnchorTimer() {
_a?.cancel();
_a = null;
_u = false;
}
}