Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Created June 17, 2025 16:07
Show Gist options
  • Save TuenTuenna/d8bb1d7489685d588914572089461a0c to your computer and use it in GitHub Desktop.
Save TuenTuenna/d8bb1d7489685d588914572089461a0c to your computer and use it in GitHub Desktop.
Dart tip of the day / Lecture 20 / Stream
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
void main() async {
// var firstUser = await getUserName();
// var secondUser = await getUserName();
// var thirdUser = await getUserName();
print('헬로우 월드');
// await for (var user in getUserNameStream()) {
// print('user : $user');
// }
// print('헬로우 월드 2');
var userNameStream =
getUserNameStream()
.asyncMap((username) {
return '$username is awesome!';
})
.distinct()
.asBroadcastStream();
StreamSubscription<String>? subscription;
subscription = userNameStream.listen(
(user) {
print('user : $user');
if (user == 'Bob') {
subscription?.cancel();
}
},
onDone: () {
print('onDone');
},
);
// userNameStream.listen(
// (user) {
// print('user : $user');
//
// if (user == 'Bob') {
// subscription?.cancel();
// }
// },
// onDone: () {
// print('onDone');
// },
// );
}
Stream<String> getUserNameStream() async* {
List<String> names = ["John", "Jane", "Bob", "Alice", "Tom"];
await Future.delayed(const Duration(seconds: 1));
yield "Bob";
await Future.delayed(const Duration(seconds: 3));
yield "Bob";
await Future.delayed(const Duration(seconds: 2));
yield names[Random().nextInt(names.length)];
}
Future<String> getUserName() async {
List<String> names = ["John", "Jane", "Bob", "Alice", "Tom"];
await Future.delayed(const Duration(seconds: 1));
return names[Random().nextInt(names.length)];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment