What’s the canonical way to share data between two providers created with riverpod? In addition those two providers might only be very loosely connected logically speaking…
Let’s assume we’ve got an application which talks to some kind of industrial valve device in a factory. There might exist a device model created with freezed which contains all the data a device might have.
@freezed
class Device with _$Device {
factory Device({
required String id,
required int temperature,
required int valvePosition,
required bool alertsEnabled,
}) = _Device;
factory Device.fromJson(Map<String, dynamic> json) => _$DeviceFromJson(json);
}
And an AsyncNotifierProvider which utilizes HTTP requests to read and update a device.
@riverpod
class Devices extends _$Devices {
@override
FutureOr<List<Device>> build() async {
// HTTP get
// return list of devices
}
Future<void> update(Device device) async {
// HTTP put
// then update state
}
}
To be backwards compatible the app should also support the old serial port API. The problem is that the old API supports quite a lot of commands, some absolutely unrelated. So one might be tempted to write a service to wrap all the commands in a class, e.g. a SerialPortService
. Yet, for devices, the only supported command of the entire API is changing the valve positions.
How would one deal with such a requirement where just a slice of the whole data needs to be updated from a different source?
I have never used the riverpod_generator, but this is the way I do it:
final provider = StateNotifierProvider<SomeNotifier, SomeState>(
(ref) {
final notifier = SomeNotifier();
ref.listen(anotherProvider, (previous, next) {
nofitier.doStuff(previous, next);
});
return notifier;
},
);
I hope this helps in some way with generated providers.
Be careful not to implement a circular dependency