Last active
May 14, 2024 22:06
-
-
Save yongjhih/37ad3fd3bdf2be7e40877489f3b05b69 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
class Post { | |
final String? content; | |
const Post([this.content]); | |
} | |
class UserProfile { | |
final List<Post> posts; | |
final int followersCount; | |
const UserProfile(this.posts, this.followersCount); | |
} | |
class User { | |
final int followersCount; | |
const User(this.followersCount); | |
} | |
class Api { | |
Future<List<Post>> getPosts() async { | |
await Future.delayed(Duration(seconds: 2)); | |
return [Post()]; | |
} | |
Future<User> getUser() async { | |
await Future.delayed(Duration(seconds: 2)); | |
return User(123); | |
} | |
} | |
extension FutureZipX<T> on Future<T> { | |
Future<(T, T2)> zipWith<T2>(Future<T2> future2) async { | |
late T result1; | |
late T2 result2; | |
await Future.wait( | |
[then((it) => result1 = it), future2.then((it) => result2 = it)]); | |
return (result1, result2); | |
} | |
} | |
void main() async { | |
final api = Api(); | |
Stopwatch stopwatch = Stopwatch()..start(); | |
UserProfile(await api.getPosts(), (await api.getUser()).followersCount); // sequential 2s + 2s | |
print(stopwatch.elapsed); // 4s~ | |
stopwatch = Stopwatch()..start(); | |
final responses = await Future.wait([api.getPosts(), api.getUser()]); // parallel w/o types // max(2s, 2s) | |
UserProfile(responses[0] as List<Post>, (responses[1] as User).followersCount); // error-prone | |
print(stopwatch.elapsed); // 2s~ | |
stopwatch = Stopwatch()..start(); | |
final (posts, user) = await api.getPosts().zipWith(api.getUser()); // parallel w/ types // max(2s, 2s) | |
final userProfile = UserProfile(posts, user.followersCount); | |
print(stopwatch.elapsed); // 2s~ | |
print(userProfile.posts.length); | |
print(userProfile.followersCount); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment