write method

Future<void> write(
  1. Measurement measurement
)

Writes a JSON encoded measurement to the file.

Implementation

Future<void> write(Measurement measurement) async {
  // Check if the sink is ready for writing...
  if (!_initialized) {
    info('File sink not ready -- delaying for 2 sec...');
    return Future.delayed(
        const Duration(seconds: 2), () => write(measurement));
  }

  final json = jsonEncode(measurement);

  await sink.then((activeSink) async {
    try {
      // always add a comma directly after json
      activeSink.write('$json\n,\n');
      debug(
          'Writing measurement to file - type: ${measurement.dataType.toString()}');

      await file.then((activeFile) async {
        await activeFile.length().then((len) {
          if (len > fileDataEndPoint.bufferSize) {
            flush(activeFile, activeSink);
          }
        });
      });
    } catch (error) {
      warning('Error writing to file - $error');
      _initialized = false;
      write(measurement);
    }
  });
}