Skip to content

Commit 92cc398

Browse files
authored
hamed/add_sync_time_cubit (#222)
- add sync time cubit
1 parent 22a914b commit 92cc398

File tree

2 files changed

+82
-0
lines changed

2 files changed

+82
-0
lines changed
+60
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
import 'dart:async';
2+
3+
import 'package:bloc/bloc.dart';
4+
5+
import 'package:flutter_deriv_api/api/response/time_response_result.dart';
6+
import 'package:flutter_deriv_api/state/server_time/server_time_cubit.dart';
7+
8+
part 'sync_time_state.dart';
9+
10+
/// Sync time cubit.
11+
class SyncTimeCubit extends Cubit<SyncTimeState> {
12+
/// Initializes Sync time cubit.
13+
SyncTimeCubit(ServerTimeCubit serverTimeCubit)
14+
: super(SyncTimeInitialState()) {
15+
_currentDateTime = now;
16+
17+
_stopwatch.start();
18+
19+
_updateDateTime(serverTimeCubit.state);
20+
_setPeriodicTimer();
21+
22+
serverTimeCubit.stream.listen(_updateDateTime);
23+
}
24+
25+
final Stopwatch _stopwatch = Stopwatch();
26+
final Duration _periodicTimerDuration = const Duration(seconds: 1);
27+
28+
late DateTime _currentDateTime;
29+
30+
/// Gets current date time.
31+
DateTime get now => state.dateTime;
32+
33+
/// Updates date time with server.
34+
Future<void> _updateDateTime(ServerTimeState serverTimeState) async {
35+
DateTime? serverTime;
36+
37+
if (serverTimeState is ServerTimeFetched) {
38+
serverTime = serverTimeState.serverTime;
39+
}
40+
41+
_currentDateTime =
42+
(serverTime ?? (await TimeResponse.fetchTime()).time)!.toUtc();
43+
44+
_stopwatch.reset();
45+
}
46+
47+
Timer _setPeriodicTimer() => Timer.periodic(
48+
_periodicTimerDuration,
49+
(_) {
50+
emit(
51+
SyncTimeUpdatedState(
52+
_currentDateTime = _currentDateTime
53+
.add(Duration(milliseconds: _stopwatch.elapsedMilliseconds)),
54+
),
55+
);
56+
57+
_stopwatch.reset();
58+
},
59+
);
60+
}
+22
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
part of 'sync_time_cubit.dart';
2+
3+
/// Sync time base state.
4+
abstract class SyncTimeState {
5+
/// Initializes sync time base state.
6+
const SyncTimeState(this.dateTime);
7+
8+
/// Keeps synced Date Time in UTC.
9+
final DateTime dateTime;
10+
}
11+
12+
/// Sync time initial state.
13+
class SyncTimeInitialState extends SyncTimeState {
14+
/// Initializes sync time initial state.
15+
SyncTimeInitialState() : super(DateTime.now().toUtc());
16+
}
17+
18+
/// Sync time updates state.
19+
class SyncTimeUpdatedState extends SyncTimeState {
20+
/// Initializes sync time updated state.
21+
SyncTimeUpdatedState(DateTime dateTime) : super(dateTime);
22+
}

0 commit comments

Comments
 (0)