Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Request data from a stream one item at time?

Tags:

flutter

dart

I'm trying to fetch data from a REST endpoint that serves a paginated response. On a button click in flutter, I would like to get the next item in the response. I think I want to use a Stream that abstracts away the paginated nature of the request, and automatically polls the next result.

Something like this dartish pseudo-code:

Stream<String> nextUrl(int lastPage=0)
{
  // Get paginated response
  batch = server.getResponse(lastPage)
  for (item in batch)
  {
      yield item;
  }
  // Recurse automatically
  // Not a problem if the stream is suspended
  // after every item request.  A big problem
  // if the stream never pauses.
  await for (String item in nextUrl(lastPage++)
  {
      yield item;
  }
}


// In flutter
class WidgetState extends state<MyPage> {
  Stream<String> urlStream = new nextUrl(0);
  String currentItem;
...
  @override
  Widget build(BuildContext context) {
      return new InkWell(
        onTap: () {
          (() async {
              // This is the call I haven't figured out.
              await item = urlStream().getNext();
              setState(() { currentItem = item; });
          })();
        }
      );
  }
}

I get the feeling that maybe something like Stream.getNext() doesn't exist? That I should be pausing / unpausing this stream? But I'm not sure how that would return only a single item at a time.

like image 427
Jordan Avatar asked Oct 15 '25 13:10

Jordan


1 Answers

The async package provide StreamQueue that allows to do that

var events = new StreamQueue<String>(yourStream);
var first = await events.next;
while (...) {
  ...
  first = await events.next;
}
like image 66
Günter Zöchbauer Avatar answered Oct 18 '25 05:10

Günter Zöchbauer