Dominic
Dominic

Reputation: 715

Stream listen() method onDone callback not being called

I can't get the onDone callback of a stream to be triggered.

I've tried cancelling the stream subscription and closing the stream controller but it doesn't work.

Here's a basic example:

Sample Code:

import 'dart:async';

void main() async {
  final streamController = StreamController<int>();

  final streamSubscription = streamController.stream.listen(
    (event) => print('Value emitted: $event'),
    onDone: () => print('Task done'),
  );

  streamController.add(1);

  await Future<void>.delayed(Duration.zero);
  await streamSubscription.cancel();
  await streamController.close();
}

Expected Output:

Value emitted: 1
Task done

Actual Output:

Value emitted: 1

Upvotes: 4

Views: 4803

Answers (1)

h8moss
h8moss

Reputation: 5020

Before you call streamController.close() you call streamSubscription.cancel(), cancelling the subscription means that you will not recieve any more events on said subscription, including onDone, that's the reason why you don't get the final event. Removing streamSubscription.cancel() or moving it to after closing the stream will work.

import 'dart:async';

void main() async {
  final streamController = StreamController<int>();

  final streamSubscription = streamController.stream.listen(
    (event) => print('Value emitted: $event'),
    onDone: () => print('Task done'),
  );

  streamController.add(1);

  await Future<void>.delayed(Duration(seconds: 1));
  // await streamSubscription.cancel() // comment this out.
  await streamController.close();
  await streamSubscription.cancel(); // <- here it is fine
}

Upvotes: 6

Related Questions