Reputation: 491
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
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
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
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