Created
March 13, 2025 07:50
-
-
Save lukas-h/df32489fbc9677d041611177c5b3b04c 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:math'; | |
import 'package:bloc/bloc.dart'; | |
Future<void> main() async { | |
// "synchronous" data structures | |
final a = 3; | |
final list = [1, 2, 3, 4, 5]; | |
for (final item in list) { | |
print(item); | |
} | |
list.forEach(print); | |
final list2 = list.map((e) => e * 2).toList(); | |
final list3 = list.where((e) => e < 3).toList(); | |
// "asynchronous" data structures | |
final b = Future.value(3); | |
print(await b); | |
await Future.delayed(Duration(seconds: 5)); | |
// "single"-subscription stream | |
final stream = Stream.fromIterable(list); | |
final sub = stream.listen(print); | |
final error = | |
stream.listen(print); // this would fail, because already subscribed to | |
// broadbast stream | |
final bStream = Stream.fromIterable(list).asBroadcastStream(); | |
final sub1 = bStream.listen(print); | |
final sub2 = bStream.listen(print); | |
final sub3 = bStream.listen(print); | |
final sub4 = bStream.listen(print); | |
bStream.where((e) => true).map((e) => e); | |
await for (final event in bStream) { | |
print(event); | |
} | |
// stream controller | |
final controller = StreamController<int>.broadcast(); | |
controller.add(3); | |
controller.addStream(bStream); | |
controller.stream.listen(print); | |
} | |
Iterable<int> listGenerator() sync* { | |
for (var i = 0; i < 10000; i++) { | |
yield i; | |
} | |
} | |
Stream<int> randomStreamGenerator() async* { | |
for (;;) { | |
await Future.delayed(Duration(seconds: 1)); | |
yield Random().nextInt(100); | |
} | |
} | |
Stream<int> streamGenerator() async* { | |
for (var i = 0;; i++) { | |
await Future.delayed(Duration(seconds: 1)); | |
yield i; | |
} | |
} | |
Stream<int> megaCoolCombinedStreamGenerator() async* { | |
yield* randomStreamGenerator(); | |
yield* streamGenerator(); | |
} | |
// async => Future | |
// async* => Stream | |
// sync* => Iterable | |
// yield => single value | |
// yield* => stream | |
// bloclibrary.dev | |
class ExampleCubit extends Cubit<int> { | |
ExampleCubit() : super(0); | |
increment() => emit(state + 1); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment