tail function

Stream<List<int>> tail(
  1. File file
)

Implementation

Stream<List<int>> tail(final File file) async* {
  final randomAccess = await file.open(mode: FileMode.read);
  var pos = await randomAccess.position();
  var len = await randomAccess.length();
  // Increase/decrease buffer size as needed.
  var buf = Uint8List(8192);

  Stream<Uint8List> _read() async* {
    while (pos < len) {
      try {
        final bytesRead = await randomAccess.readInto(buf);
        pos += bytesRead;

        yield buf.sublist(0, bytesRead);
      } catch (E) {}
    }
  }

  // Step 1: read whole file
  yield* _read();

  // Step 2: wait for modify events and read more bytes from file
  await for (final event in file.watch(events: FileSystemEvent.modify)) {
    if ((event as FileSystemModifyEvent).contentChanged) {
      try {
        len = await (randomAccess.length());
        yield* _read();
      } catch (E) {}
    }
  }
}