57 lines
2.0 KiB
Dart
57 lines
2.0 KiB
Dart
import 'dart:async';
|
|
import 'package:connectivity_plus/connectivity_plus.dart';
|
|
import 'package:get/get.dart';
|
|
|
|
/// [ConnectionService] is a GetX Service that monitors internet connectivity status.
|
|
///
|
|
/// It utilizes the [Connectivity] class from the `connectivity_plus` package.
|
|
class ConnectionService extends GetxService {
|
|
final Connectivity _connectivity = Connectivity();
|
|
|
|
/// Subscription to the connectivity change stream.
|
|
late StreamSubscription<List<ConnectivityResult>> _subscription;
|
|
|
|
/// Reactive boolean to indicate the current internet connection status.
|
|
/// `true` means the device is connected to the internet via Wi-Fi, mobile data, or other means.
|
|
final RxBool isConnected = true.obs;
|
|
|
|
bool get isCurrentlyConnected => isConnected.value;
|
|
|
|
/// Called when the service is first initialized.
|
|
@override
|
|
void onInit() {
|
|
super.onInit();
|
|
_initConnectivity();
|
|
_subscription = _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
|
|
}
|
|
|
|
/// Checks the initial connectivity status when the service is initialized.
|
|
Future<void> _initConnectivity() async {
|
|
try {
|
|
final result = await _connectivity.checkConnectivity();
|
|
_updateConnectionStatus(result); // Wrap in a list for consistency
|
|
} catch (e) {
|
|
isConnected.value = false;
|
|
}
|
|
}
|
|
|
|
/// Callback function to handle changes in connectivity status.
|
|
/// @param results A list of [ConnectivityResult] representing all active network connections.
|
|
void _updateConnectionStatus(List<ConnectivityResult> results) {
|
|
// If all results are `none`, the device is considered offline.
|
|
isConnected.value = results.any((result) => result != ConnectivityResult.none);
|
|
}
|
|
|
|
Future<bool> checkConnection() async {
|
|
final result = await _connectivity.checkConnectivity();
|
|
return !result.contains(ConnectivityResult.none);
|
|
}
|
|
|
|
/// Cancels the connectivity subscription when the service is closed.
|
|
@override
|
|
void onClose() {
|
|
_subscription.cancel();
|
|
super.onClose();
|
|
}
|
|
}
|