@@ -32,13 +32,9 @@ class ConnectionCubit extends Cubit<ConnectionState> {
32
32
33
33
_connectionInformation = connectionInformation;
34
34
35
- if (_api is BinaryAPI ) {
36
- _setupConnectivityListener ();
37
- }
35
+ _connect (_connectionInformation);
38
36
39
37
_startKeepAliveTimer ();
40
-
41
- _connect (_connectionInformation);
42
38
}
43
39
44
40
final String _key = '${UniqueKey ()}' ;
@@ -74,6 +70,9 @@ class ConnectionCubit extends Cubit<ConnectionState> {
74
70
/// Gets app id of websocket.
75
71
static String get appId => _connectionInformation.appId;
76
72
73
+ /// Streamsubscription for connectivity.
74
+ StreamSubscription <ConnectivityResult >? connectivitySubscription;
75
+
77
76
/// Reconnect to Websocket.
78
77
Future <void > reconnect ({ConnectionInformation ? connectionInformation}) async {
79
78
emit (const ConnectionDisconnectedState ());
@@ -122,26 +121,30 @@ class ConnectionCubit extends Cubit<ConnectionState> {
122
121
}
123
122
},
124
123
);
124
+
125
+ if (_api is BinaryAPI ) {
126
+ _setupConnectivityListener ();
127
+ }
125
128
}
126
129
127
- void _setupConnectivityListener () =>
128
- Connectivity ().onConnectivityChanged.listen (
129
- (ConnectivityResult status) async {
130
- final bool isConnectedToNetwork =
131
- status == ConnectivityResult .mobile ||
132
- status == ConnectivityResult .wifi;
133
-
134
- if (isConnectedToNetwork) {
135
- final bool isConnected = await _ping ();
136
-
137
- if (! isConnected) {
138
- await reconnect ();
139
- }
140
- } else if (status == ConnectivityResult .none) {
141
- emit (const ConnectionDisconnectedState ());
130
+ void _setupConnectivityListener () {
131
+ connectivitySubscription ?? = Connectivity ().onConnectivityChanged.listen (
132
+ (ConnectivityResult status) async {
133
+ final bool isConnectedToNetwork = status == ConnectivityResult .mobile ||
134
+ status == ConnectivityResult .wifi;
135
+
136
+ if (isConnectedToNetwork) {
137
+ final bool isConnected = await _ping ();
138
+
139
+ if (! isConnected) {
140
+ await reconnect ();
142
141
}
143
- },
144
- );
142
+ } else if (status == ConnectivityResult .none) {
143
+ emit (const ConnectionDisconnectedState ());
144
+ }
145
+ },
146
+ );
147
+ }
145
148
146
149
void _startKeepAliveTimer () {
147
150
if (_connectivityTimer == null || ! _connectivityTimer! .isActive) {
@@ -154,7 +157,6 @@ class ConnectionCubit extends Cubit<ConnectionState> {
154
157
try {
155
158
final PingResponse response =
156
159
await PingResponse .pingMethod ().timeout (_pingTimeout);
157
-
158
160
return response.ping == PingEnum .pong;
159
161
} on Exception catch (_) {
160
162
return false ;
@@ -164,7 +166,8 @@ class ConnectionCubit extends Cubit<ConnectionState> {
164
166
@override
165
167
Future <void > close () {
166
168
_connectivityTimer? .cancel ();
167
-
169
+ connectivitySubscription? .cancel ();
170
+ connectivitySubscription = null ;
168
171
return super .close ();
169
172
}
170
173
}
0 commit comments