Last active
August 31, 2024 13:20
-
-
Save yongjhih/c5a1971f19914695c1d971fcd3ecbe49 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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