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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With