Flutter run async function on stream listen

0 votes

I have a stream of data that gets me messages, and on each message, I want to execute an HTTP request, i.e. an async function. How can I do that?

Minimum reproducible example:

Future<int> myFuture(int n) async {
  Future.delayed(Duration(seconds: 2));  // Mock future
  print("Future finished for: $n");
  return n;
}

Stream<int> countStream(int to) async* {
  for (int i = 1; i <= to; i++) {
    yield i;
  }
}

void main() async {
  var stream = countStream(10);
  stream.listen((n) { await myFuture(n); });
  // or simply: stream.listen(myFuture);
}

Essentially I can't await myFuture.

Mar 16, 2023 in Android by sarit
• 1,830 points
2,500 views

1 answer to this question.

0 votes

You can make the listen callback an async function, and then await the call to myFuture. Here's an updated version of your example code:

Future<int> myFuture(int n) async {
  await Future.delayed(Duration(seconds: 2));  // Mock future
  print("Future finished for: $n");
  return n;
}

Stream<int> countStream(int to) async* {
  for (int i = 1; i <= to; i++) {
    yield i;
  }
}

void main() async {
  var stream = countStream(10);
  stream.listen((n) async {
    await myFuture(n);
  });
}

Alternatively, you could use the asyncMap method on the Stream object to apply the asynchronous operation to each element of the stream:

void main() async {
  var stream = countStream(10);
  await for (var result in stream.asyncMap((n) => myFuture(n))) {
    // do something with the result
  }
}

In this example, asyncMap applies the myFuture function to each element of the stream, and returns a new stream containing the results. The await for loop then iterates over the results of the new stream.

To know more, join our Flutter Training today.

answered Mar 20, 2023 by pooja

Related Questions In Android

0 votes
1 answer
0 votes
1 answer

How to run code after some delay in Flutter?

You can use the Future.delayed method to ...READ MORE

answered Mar 10, 2023 in Android by vinayak
1,673 views
0 votes
1 answer

flutter remove back button on appbar

You can remove the back button from ...READ MORE

answered Mar 10, 2023 in Android by vinayak
16,746 views