recordFw<T> method

Future<Fw<T>> recordFw<T>({
  1. required int id,
  2. required BiDi<R, T> bidi,
  3. required T defaultValue,
  4. required DspReg disposers,
})

Implementation

Future<Fw<T>> recordFw<T>({
  required int id,
  required BiDi<R, T> bidi,
  required T defaultValue,
  required DspReg disposers,
}) async {
  T parse(R? record) => record?.let(bidi.forward) ?? defaultValue;

  final resultDsp = DspImpl();
  final result = resultDsp.fw(
    parse(
      await get(id),
    ),
  );

  final listening = watchObject(
    id,
    fireImmediately: true,
  ).map(parse).listen(result.set);

  final updates = StreamController<T>()..closeBy(disposers);

  updates.stream.asyncForEach((value) async {
    await isar.writeTxn(() async {
      await put(
        bidi.backward(value)..id = id,
      );
    });
  }).awaitBy(disposers);

  disposers.add(() async {
    await listening.cancel();
    await resultDsp.dispose();
  });

  return Fw.fromFr(
    fr: result,
    set: (value) {
      updates.add(value);
      result.set(value);
    },
  );
}