Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to get notified when a dart stream gets its first result?

Tags:

flutter

dart

I currently have an async function that does the following:

  1. Initializes the stream
  2. Call stream.listen() and provide a function to listen to the stream.
  3. await for the stream to get its first result.

The following is some pseudo code of my function:

Future<void> initStream() async {
  // initialize stream
  var stream = getStream();
  // listen
  stream.listen((result) {
    // do some stuff here
  });
  // await until first result
  await stream.first; // gives warning
}

Unfortunately it seems that calling stream.first counts as listening to the stream, and streams are not allowed to be listened by multiple...listeners?

I tried a different approach by using await Future.doWhile() Something like the following:

bool gotFirstResult = false;
Future<void> initStream() async {
  var stream = getStream();
  stream.listen((result) {
    // do some stuff here
    gotFirstResult = true;
  });
  await Future.doWhile(() => !gotFirstResult);
}

This didn't work for me, and I still don't know why. Future.doWhile() was successfully called, but then the function provided to stream.listen() was never called in this case.

Is there a way to wait for the first result of a stream? (I'm sorry if I didn't describe my question well enough. I'll definitely add other details if needed.) Thanks in advance!

like image 682
Allen Hu Avatar asked Mar 02 '23 02:03

Allen Hu


1 Answers

One way is converting your stream to broadcast one:

var stream = getStream().asBroadcastStream();
stream.listen((result) {
  // do some stuff here
});
await stream.first;
like image 116
Pavel Avatar answered Mar 05 '23 12:03

Pavel