Home > Net >  Yield another broadcast stream with Dart
Yield another broadcast stream with Dart

Time:07-25

I am trying to yield* a broadcast stream but for some reason, it does not work as I expected.

The Firebase/FlutterFire library seems to be doing it that way.

import 'dart:async';

final controller = StreamController<int>.broadcast();

Stream<int> getStream() async* {
  yield 1;
  yield* controller.stream;
}

void main() {
  controller.add(0);

  getStream().listen(
    (event) => print('BC Event: $event'),
    onDone: () => print('BC Done'),
    one rror: (error) => print(error),
  );

  controller.add(2);
  controller.close();
}

Expected:

BC Event: 1
BC Event: 2
BC Done

Actual:

BC Event: 1
BC Done

Any idea?

CodePudding user response:

i think the problems is that you closes the listen event too soon, before the stream can return the second value

i tested with a timer and it worked

import 'dart:async';

final controller = StreamController<int>.broadcast();

Stream<int> getStream() async* {
  yield 1;
  yield* controller.stream;
}

void main() async {
  controller.add(0);

  getStream().listen(
    (event) => print('BC Event: $event'),
    onDone: () => print('BC Done'),
    one rror: (error) => print(error),
  );
  
  
  await Future.delayed(Duration(seconds: 1));
  controller.add(2);
  controller.add(3);
  controller.add(4);
  controller.close();
}
  • Related