Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 940
seongjoo Avatar asked Oct 02 '14 05:10

seongjoo


People also ask

How do I stop a stream from flutter?

Cancel a stream In flutter, streams are usually used with the StreamBuilder which manages and unsubscribes from a stream for you internally once the widget is destroyed. A good rule to follow is when you subscribe to a stream, keep the Subscription and write the code in the dispose method to call cancel.

How do Dart streams work?

To create a new Stream type, you can just extend the Stream class and implement the listen() method—all other methods on Stream call listen() in order to work. The listen() method allows you to start listening on a stream. Until you do so, the stream is an inert object describing what events you want to see.

What is StreamSubscription?

A subscription on events from a Stream. When you listen on a Stream using Stream. listen, a StreamSubscription object is returned. The subscription provides events to the listener, and holds the callbacks used to handle the events.


2 Answers

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
like image 54
Günter Zöchbauer Avatar answered Oct 03 '22 00:10

Günter Zöchbauer


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.)

like image 43
Jens Avatar answered Oct 03 '22 01:10

Jens