network_monitor.dart 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. import 'dart:async';
  2. import 'package:connectivity_plus/connectivity_plus.dart';
  3. import 'package:flowy_sdk/log.dart';
  4. import 'package:flowy_sdk/dispatch/dispatch.dart';
  5. import 'package:flowy_sdk/protobuf/flowy-net/network_state.pb.dart';
  6. import 'package:flutter/services.dart';
  7. class NetworkListener {
  8. final Connectivity _connectivity = Connectivity();
  9. late StreamSubscription<ConnectivityResult> _connectivitySubscription;
  10. NetworkListener() {
  11. _connectivitySubscription = _connectivity.onConnectivityChanged.listen(_updateConnectionStatus);
  12. }
  13. Future<void> start() async {
  14. late ConnectivityResult result;
  15. // Platform messages may fail, so we use a try/catch PlatformException.
  16. try {
  17. result = await _connectivity.checkConnectivity();
  18. } on PlatformException catch (e) {
  19. Log.error('Couldn\'t check connectivity status. $e');
  20. return;
  21. }
  22. return _updateConnectionStatus(result);
  23. }
  24. void stop() {
  25. _connectivitySubscription.cancel();
  26. }
  27. Future<void> _updateConnectionStatus(ConnectivityResult result) async {
  28. final networkType = () {
  29. switch (result) {
  30. case ConnectivityResult.wifi:
  31. return NetworkType.Wifi;
  32. case ConnectivityResult.ethernet:
  33. return NetworkType.Ethernet;
  34. case ConnectivityResult.mobile:
  35. return NetworkType.Cell;
  36. case ConnectivityResult.none:
  37. return NetworkType.UnknownNetworkType;
  38. case ConnectivityResult.bluetooth:
  39. return NetworkType.UnknownNetworkType;
  40. }
  41. }();
  42. Log.info("Network type: $networkType");
  43. final state = NetworkState.create()..ty = networkType;
  44. NetworkEventUpdateNetworkType(state).send().then((result) {
  45. result.fold(
  46. (l) {},
  47. (e) => Log.error(e),
  48. );
  49. });
  50. }
  51. }