Created
August 3, 2023 14:50
-
-
Save hawkkiller/932140079adfdcab2cfdd4b0292bb50a to your computer and use it in GitHub Desktop.
Event Loop unloading
This file contains hidden or 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 'package:crypto/crypto.dart'; | |
| import 'package:flutter/material.dart'; | |
| void main() { | |
| runApp(const MainApp()); | |
| } | |
| class MainApp extends StatefulWidget { | |
| const MainApp({super.key}); | |
| @override | |
| State<MainApp> createState() => _MainAppState(); | |
| } | |
| class _MainAppState extends State<MainApp> { | |
| bool optimized = false; | |
| @override | |
| Widget build(BuildContext context) { | |
| return MaterialApp( | |
| home: Scaffold( | |
| body: Center( | |
| child: Column( | |
| mainAxisAlignment: MainAxisAlignment.center, | |
| children: [ | |
| Switch( | |
| value: optimized, | |
| onChanged: (value) { | |
| setState(() { | |
| optimized = value; | |
| }); | |
| }, | |
| ), | |
| TextButton( | |
| onPressed: () { | |
| final stopWatch = Stopwatch()..start(); | |
| fetch(optimized).toList().then( | |
| (v) { | |
| Zone.current.print( | |
| 'Processed ${v.length} elements in ${stopWatch.elapsedMilliseconds}ms'); | |
| }, | |
| ); | |
| }, | |
| child: const Text('Perform Heavy Operation'), | |
| ), | |
| const CircularProgressIndicator(), | |
| ], | |
| ), | |
| ), | |
| ), | |
| ); | |
| } | |
| } | |
| Stream<String> fetch(bool optimize) { | |
| // perform operation to get your data | |
| final data = generateData(); | |
| return Stream.fromIterable(data).asyncMap<String>( | |
| (e) { | |
| if (optimize) { | |
| return Future(() => e); | |
| } | |
| return e; | |
| }, | |
| ).map((event) => sha1.convert(event.codeUnits).toString()); | |
| } | |
| // generate string with length of index | |
| Iterable<String> generateData() => Iterable.generate( | |
| 10000, | |
| (index) => 'a' * index, | |
| ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment