onNetworkChange property

Stream<ConnectivityResult> get onNetworkChange

Returns a stream broadcasting the ConnectivityResult of the browser.

Implementation

static Stream<ConnectivityResult> get onNetworkChange {
  StreamController<ConnectivityResult>? controller;

  // Event listener reacting on window focus events.
  void changeListener(web.Event event) =>
      // TODO: Rely on `NetworkInformation.type` when it's available:
      //       https://developer.mozilla.org/en-US/docs/Web/API/NetworkInformation/type
      controller!.add(switch (web.window.navigator.onLine) {
        false => ConnectivityResult.none,
        true => ConnectivityResult.wifi,
      });

  controller = StreamController(
    onListen: () {
      web.window.navigator.connection.addEventListener(
        'change',
        changeListener.toJS,
      );
    },
    onCancel: () {
      web.window.navigator.connection.removeEventListener(
        'change',
        changeListener.toJS,
      );
    },
  );

  return controller.stream;
}