seongjoo
seongjoo

Reputation: 491

How do I check the end of Stream in Dart?

fellow dart programmers.

I am reading in a file using Stream as below.

Stream<List<int>> stream = new File(filepath).openRead();
stream
    .transform(UTF8.decoder)
    .transform(const LineSpilitter())
    .listen((line){
        // TODO: check if this is the last line of the file
        var isLastLine;
    });

I want to check whether the line in listen() is the last line of the file.

Upvotes: 6

Views: 7557

Answers (3)

dwb
dwb

Reputation: 2624

You can add a simple handler similar to .handleError(), which works nicely with .forEach() and .map() and other high-level APIs.

extension StreamExtension<T> on Stream<T> {
  Stream<T> handleOnDone(void Function() onDone) async* {
    await for (final T obj in this) {
      yield obj;
    }
    onDone();
  }
}

Then use it like:

final Stream<int> stream = ... ;
stream
  .handleError((e) { .. })
  .handleOnDone(() {
    print('Stream finished!');
  })
  .forEach((n) { .. });

Upvotes: 0

Jens
Jens

Reputation: 2702

While the answer from @Günter Zöchbauer works, the last property of streams accomplishes exactly what you are asking for (I guess the dart team added this functionality in the last 5 years).

Stream<List<int>> stream = new File('main.dart').openRead();
List<int> last = await stream.last;

But note: It is not possible to listen to the stream and use await stream.last.

This will cause an error:

StateError (Bad state: Stream has already been listened to.)

Upvotes: 4

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657198

I don't think you can check if the current chunk of data is the last one.
You can only pass a callback that is called when the stream is closed.

Stream<List<int>> stream = new File('main.dart').openRead();
  stream.
  .transform(UTF8.decoder)
  .transform(const LineSpilitter())
  .listen((line) {
// TODO: check if this is the last line of the file
    var isLastLine;
  }
  ,onDone: (x) => print('done')); // <= add a second callback

Upvotes: 8

Related Questions