@@ -14,7 +14,7 @@ import 'package:flutter_deriv_api/services/connection/api_manager/enums.dart';
14
14
15
15
part 'connection_state.dart' ;
16
16
17
- /// Bringing [ConnectionCubit] to flutter-deriv-api to simplify the usage of api .
17
+ /// [ConnectionCubit] is a [Cubit] which manages connection status of websocket .
18
18
class ConnectionCubit extends Cubit <ConnectionState > {
19
19
/// Initializes [ConnectionCubit] .
20
20
ConnectionCubit (
@@ -23,9 +23,8 @@ class ConnectionCubit extends Cubit<ConnectionState> {
23
23
this .enableDebug = false ,
24
24
this .printResponse = false ,
25
25
}) : super (const ConnectionInitialState ()) {
26
- APIInitializer ().initialize (
27
- api: api ?? BinaryAPI (key: _key, enableDebug: enableDebug),
28
- );
26
+ APIInitializer ()
27
+ .initialize (api: api ?? BinaryAPI (key: _key, enableDebug: enableDebug));
29
28
30
29
_api = Injector ()< BaseAPI > ();
31
30
@@ -46,6 +45,9 @@ class ConnectionCubit extends Cubit<ConnectionState> {
46
45
/// Default value is `false` .
47
46
final bool printResponse;
48
47
48
+ /// Connection status of websocket stream subscription.
49
+ StreamSubscription <APIStatus >? _connectionStatusSubscription;
50
+
49
51
static late ConnectionInformation _connectionInformation;
50
52
51
53
/// Gets connection information of WebSocket (endpoint, brand, appId).
@@ -80,18 +82,35 @@ class ConnectionCubit extends Cubit<ConnectionState> {
80
82
}
81
83
82
84
void _handleConnectionStatus () {
83
- _api! .connectionStatus.listen ((APIStatus status) {
84
- switch (status) {
85
- case APIStatus .connecting:
86
- emit (const ConnectionConnectingState ());
87
- break ;
88
- case APIStatus .connected:
89
- emit (const ConnectionConnectedState ());
90
- break ;
91
- case APIStatus .disconnected:
92
- emit (const ConnectionDisconnectedState ());
93
- break ;
94
- }
95
- });
85
+ _cancelConnectionStatusSubscription ();
86
+
87
+ _connectionStatusSubscription = _api! .connectionStatus.listen (
88
+ (APIStatus status) {
89
+ switch (status) {
90
+ case APIStatus .connecting:
91
+ emit (const ConnectionConnectingState ());
92
+ break ;
93
+ case APIStatus .connected:
94
+ emit (const ConnectionConnectedState ());
95
+ break ;
96
+ case APIStatus .disconnected:
97
+ emit (const ConnectionDisconnectedState ());
98
+ break ;
99
+ }
100
+ },
101
+ );
102
+ }
103
+
104
+ void _cancelConnectionStatusSubscription () {
105
+ if (_connectionStatusSubscription != null ) {
106
+ _connectionStatusSubscription! .cancel ();
107
+ }
108
+ }
109
+
110
+ @override
111
+ Future <void > close () {
112
+ _cancelConnectionStatusSubscription ();
113
+
114
+ return super .close ();
96
115
}
97
116
}
0 commit comments