1
import 'dart:async';
2

3
import 'package:connectivity/connectivity.dart';
4

5 13
StreamTransformer<ConnectivityResult, ConnectivityResult> debounce(
6
  Duration debounceDuration,
7
) {
8
  bool _seenFirstData = false;
9
  Timer _debounceTimer;
10

11 13
  return StreamTransformer<ConnectivityResult, ConnectivityResult>.fromHandlers(
12 13
    handleData: (ConnectivityResult data, EventSink<ConnectivityResult> sink) {
13
      if (_seenFirstData) {
14 13
        _debounceTimer?.cancel();
15 13
        _debounceTimer = Timer(debounceDuration, () => sink.add(data));
16
      } else {
17 13
        sink.add(data);
18
        _seenFirstData = true;
19
      }
20
    },
21 13
    handleDone: (EventSink<ConnectivityResult> sink) {
22 13
      _debounceTimer?.cancel();
23 13
      sink.close();
24
    },
25
  );
26
}
27

28 13
StreamTransformer<ConnectivityResult, ConnectivityResult> startsWith(
29
  ConnectivityResult data,
30
) {
31 13
  return StreamTransformer<ConnectivityResult, ConnectivityResult>(
32 13
    (
33
      Stream<ConnectivityResult> input,
34
      bool cancelOnError,
35
    ) {
36
      StreamController<ConnectivityResult> controller;
37
      StreamSubscription<ConnectivityResult> subscription;
38

39 13
      controller = StreamController<ConnectivityResult>(
40
        sync: true,
41 13
        onListen: () => controller?.add(data),
42 13
        onPause: ([Future<dynamic> resumeSignal]) => subscription.pause(resumeSignal),
43 13
        onResume: () => subscription.resume(),
44 13
        onCancel: () => subscription.cancel(),
45
      );
46

47 13
      subscription = input.listen(
48 13
        controller.add,
49 13
        onError: controller.addError,
50 13
        onDone: controller.close,
51
        cancelOnError: cancelOnError,
52
      );
53

54 13
      return controller.stream.listen(null);
55
    },
56
  );
57
}

Read our documentation on viewing source code .

Loading