Skip to content

Instantly share code, notes, and snippets.

@yongjhih
Last active August 31, 2024 13:20
Show Gist options
  • Save yongjhih/c5a1971f19914695c1d971fcd3ecbe49 to your computer and use it in GitHub Desktop.
Save yongjhih/c5a1971f19914695c1d971fcd3ecbe49 to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
Stream<Iterable<Map<String, dynamic>?>?> fetchGitHubRepos(String? url) async* {
while (url != null) {
print("$url");
final response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
yield (jsonDecode(response.body) as List?)?.map((it) => it as Map<String, dynamic>?);
final linkHeader = response.headers['link'];
url = linkHeader != null
? RegExp(r'<([^>]+)>;\s*rel="next"').firstMatch(linkHeader)?.group(1)
: null;
} else {
throw Exception('Failed to load repos');
}
}
}
void main() async {
final url = 'https://api.github.com/users/yongjhih/repos';
final stream = fetchGitHubRepos(url)
.asyncExpand((it) => Stream.fromIterable(it ?? <Map<String, dynamic>?>[]))
.take(3);
await for (final repo in stream) {
print(repo?['name'] ?? "");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment