-
Notifications
You must be signed in to change notification settings - Fork 25
/
connection_state_provider.dart
55 lines (48 loc) · 1.69 KB
/
connection_state_provider.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import 'package:cobble/domain/entities/pebble_device.dart';
import 'package:cobble/infrastructure/pigeons/pigeons.g.dart';
import 'package:hooks_riverpod/hooks_riverpod.dart';
class WatchConnectionState {
final bool? isConnected;
final bool? isConnecting;
final String? currentWatchAddress;
final PebbleDevice? currentConnectedWatch;
WatchConnectionState(this.isConnected, this.isConnecting,
this.currentWatchAddress, this.currentConnectedWatch);
}
class ConnectionCallbacksStateNotifier
extends StateNotifier<WatchConnectionState> implements ConnectionCallbacks {
final _connectionControl = ConnectionControl();
ConnectionCallbacksStateNotifier()
: super(WatchConnectionState(false, false, null, null)) {
ConnectionCallbacks.setup(this);
_connectionControl.observeConnectionChanges();
}
@override
void onWatchConnectionStateChanged(WatchConnectionStatePigeon pigeon) {
state = WatchConnectionState(
pigeon.isConnected,
pigeon.isConnecting,
pigeon.currentWatchAddress,
PebbleDevice.fromPigeon(pigeon.currentConnectedWatch));
}
@override
void dispose() {
ConnectionCallbacks.setup(null);
_connectionControl.cancelObservingConnectionChanges();
//XXX: Potentially a bug in riverpod
if (mounted) {
super.dispose();
}
}
}
final AutoDisposeStateNotifierProvider<ConnectionCallbacksStateNotifier, WatchConnectionState>
connectionStateProvider =
StateNotifierProvider.autoDispose<ConnectionCallbacksStateNotifier, WatchConnectionState>((ref) {
final notifier = ConnectionCallbacksStateNotifier();
ref.onDispose(() {
if (notifier.mounted) {
notifier.dispose();
}
});
return notifier;
});