|
| 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 | +} |
0 commit comments