40 lines
1.1 KiB
Dart
40 lines
1.1 KiB
Dart
import 'dart:async';
|
|
import 'package:nb_utils/nb_utils.dart';
|
|
|
|
class NetConnectionCallback {
|
|
static final NetConnectionCallback _singleton = NetConnectionCallback._internal();
|
|
|
|
factory NetConnectionCallback() {
|
|
return _singleton;
|
|
}
|
|
|
|
NetConnectionCallback._internal();
|
|
|
|
// Use a StreamController to broadcast network status changes
|
|
final StreamController<bool> _connectionChangeController = StreamController<bool>.broadcast();
|
|
|
|
// Expose the stream
|
|
Stream<bool> get connectionChange => _connectionChangeController.stream;
|
|
|
|
// Method to check current network status and emit to stream
|
|
void checkConnection() {
|
|
isNetworkAvailable().then((hasConnection) {
|
|
_connectionChangeController.add(hasConnection);
|
|
});
|
|
}
|
|
|
|
// Initialize and start periodic checking
|
|
void initialize() {
|
|
// Check connection status initially
|
|
checkConnection();
|
|
|
|
// Set up periodic check (every 5 seconds)
|
|
Timer.periodic(Duration(seconds: 5), (timer) {
|
|
checkConnection();
|
|
});
|
|
}
|
|
|
|
void dispose() {
|
|
_connectionChangeController.close();
|
|
}
|
|
} |