forked from deriv-com/flutter-deriv-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver_time_cubit.dart
60 lines (47 loc) · 1.76 KB
/
server_time_cubit.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import 'dart:async';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:flutter_deriv_api/api/response/time_response_result.dart';
import 'package:flutter_deriv_api/helpers/helpers.dart';
import 'package:flutter_deriv_api/state/connection/connection_cubit.dart';
part 'server_time_state.dart';
/// A cubit to fetch and sync machine time with server time.
class ServerTimeCubit extends Cubit<ServerTimeState> {
/// Initializes [ServerTimeCubit].
ServerTimeCubit(ConnectionCubit connectionCubit)
: super(InitialServerTime()) {
_connectionSubscription =
connectionCubit.stream.listen(_connectionListener);
}
late final StreamSubscription<ConnectionState> _connectionSubscription;
final Duration _fetchServerTimeDuration = const Duration(seconds: 90);
final Duration _fetchServerTimeTimeoutDuration = const Duration(seconds: 5);
Timer? _serverTimeInterval;
void _connectionListener(ConnectionState state) {
_fetchServerTime(state);
if (_serverTimeInterval != null && _serverTimeInterval!.isActive) {
_serverTimeInterval!.cancel();
}
_serverTimeInterval = Timer.periodic(
_fetchServerTimeDuration,
(Timer timer) => _fetchServerTime(state),
);
}
Future<void> _fetchServerTime(ConnectionState state) async {
if (state is ConnectionConnectedState) {
try {
final TimeResponse serverTime = await TimeResponse.fetchTime()
.timeout(_fetchServerTimeTimeoutDuration);
emit(ServerTimeFetched(serverTime: serverTime.time));
} on Exception catch (e) {
emit(ServerTimeError('$e'));
}
} else {
_serverTimeInterval?.cancel();
}
}
@override
Future<void> close() async {
await _connectionSubscription.cancel();
return super.close();
}
}