isolate sample maintenance (#167)

* isolate sample maintenance

- use slightly more meaningful names
- rename files
- misc small readability changes

* update MAINTENANCE.md

* fix gh username

* formatting

* upgrade dependencies
pull/170/head
John Ryan 5 years ago committed by GitHub
parent 23d71e057d
commit f325e685d1
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

@ -10,7 +10,7 @@ match any new language/SDK features, etc.).
| chrome-os-best-practices | | | | chrome-os-best-practices | | |
| experimental | | | | experimental | | |
| flutter_maps_firestore | | | | flutter_maps_firestore | | |
| isolate_example | redbrogdon | 9/12/19 | | isolate_example | johnpryan | 11/21/19 |
| jsonexample | | | | jsonexample | | |
| material_studies/shrine | | | | material_studies/shrine | | |
| place_tracker | | | | place_tracker | | |

@ -142,7 +142,9 @@ class DataTransferIsolateController extends ChangeNotifier {
} }
Future<void> generateRandomNumbers(bool transferableTyped) async { Future<void> generateRandomNumbers(bool transferableTyped) async {
if (running) return; if (running) {
return;
}
if (transferableTyped) { if (transferableTyped) {
runningTest = 2; runningTest = 2;
@ -150,7 +152,7 @@ class DataTransferIsolateController extends ChangeNotifier {
runningTest = 1; runningTest = 1;
} }
Random rng = Random(); var random = Random();
currentProgress.clear(); currentProgress.clear();
@ -162,7 +164,7 @@ class DataTransferIsolateController extends ChangeNotifier {
randNums.clear(); randNums.clear();
for (int j = 0; j < 1000000; j++) { for (int j = 0; j < 1000000; j++) {
randNums.add(rng.nextInt(100)); randNums.add(random.nextInt(100));
} }
if (transferableTyped) { if (transferableTyped) {
@ -221,28 +223,28 @@ class RunningList extends StatelessWidget {
} }
} }
Future<void> _secondIsolateEntryPoint(SendPort callerSP) async { Future<void> _secondIsolateEntryPoint(SendPort sendPort) async {
ReceivePort newIceRP = ReceivePort(); var receivePort = ReceivePort();
callerSP.send(newIceRP.sendPort); sendPort.send(receivePort.sendPort);
int length = 1; int length = 1;
newIceRP.listen( receivePort.listen(
(dynamic message) async { (dynamic message) async {
if (message is String && message == 'start') { if (message is String && message == 'start') {
await generateAndSum(callerSP, createNums(), length); await generateAndSum(sendPort, createNums(), length);
callerSP.send('done'); sendPort.send('done');
} else if (message is TransferableTypedData) { } else if (message is TransferableTypedData) {
await generateAndSum( await generateAndSum(
callerSP, message.materialize().asInt32List(), length); sendPort, message.materialize().asInt32List(), length);
length++; length++;
} else if (message is List<int>) { } else if (message is List<int>) {
await generateAndSum(callerSP, message, length); await generateAndSum(sendPort, message, length);
length++; length++;
} }
if (length == 101) { if (length == 101) {
callerSP.send('done'); sendPort.send('done');
length = 1; length = 1;
} }
}, },
@ -250,9 +252,9 @@ Future<void> _secondIsolateEntryPoint(SendPort callerSP) async {
} }
Iterable<int> createNums() sync* { Iterable<int> createNums() sync* {
final rng = Random(); var random = Random();
for (int i = 0; i < 100000000; i++) { for (int i = 0; i < 100000000; i++) {
yield rng.nextInt(100); yield random.nextInt(100);
} }
} }

@ -102,7 +102,7 @@ class InfiniteProcessPage extends StatelessWidget {
class InfiniteProcessIsolateController extends ChangeNotifier { class InfiniteProcessIsolateController extends ChangeNotifier {
Isolate newIsolate; Isolate newIsolate;
ReceivePort mIceRP; ReceivePort receivePort;
SendPort newIceSP; SendPort newIceSP;
Capability capability; Capability capability;
@ -120,12 +120,13 @@ class InfiniteProcessIsolateController extends ChangeNotifier {
List<int> get currentResults => _currentResults; List<int> get currentResults => _currentResults;
Future<void> createIsolate() async { Future<void> createIsolate() async {
mIceRP = ReceivePort(); receivePort = ReceivePort();
newIsolate = await Isolate.spawn(_secondIsolateEntryPoint, mIceRP.sendPort); newIsolate =
await Isolate.spawn(_secondIsolateEntryPoint, receivePort.sendPort);
} }
void listen() { void listen() {
mIceRP.listen((dynamic message) { receivePort.listen((dynamic message) {
if (message is SendPort) { if (message is SendPort) {
newIceSP = message; newIceSP = message;
newIceSP.send(_currentMultiplier); newIceSP.send(_currentMultiplier);
@ -224,7 +225,9 @@ Future<void> _secondIsolateEntryPoint(SendPort callerSP) async {
callerSP.send(newIceRP.sendPort); callerSP.send(newIceRP.sendPort);
newIceRP.listen((dynamic message) { newIceRP.listen((dynamic message) {
if (message is int) multiplyValue = message; if (message is int) {
multiplyValue = message;
}
}); });
// This runs until the isolate is terminated. // This runs until the isolate is terminated.

@ -14,19 +14,19 @@
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'page_one.dart'; import 'data_transfer_page.dart';
import 'page_three.dart'; import 'infinite_process_page.dart';
import 'page_two.dart'; import 'performance_page.dart';
void main() { void main() {
runApp( runApp(
MaterialApp( MaterialApp(
home: StartApp(), home: HomePage(),
), ),
); );
} }
class StartApp extends StatelessWidget { class HomePage extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
return MaterialApp( return MaterialApp(

@ -17,15 +17,15 @@ import 'package:flutter/material.dart';
// Computes the nth number in the Fibonacci sequence. // Computes the nth number in the Fibonacci sequence.
int fib(int n) { int fib(int n) {
int number1 = n - 1; var a = n - 1;
int number2 = n - 2; var b = n - 2;
if (n == 1) { if (n == 1) {
return 0; return 0;
} else if (n == 0) { } else if (n == 0) {
return 1; return 1;
} else { } else {
return (fib(number1) + fib(number2)); return (fib(a) + fib(b));
} }
} }
@ -49,25 +49,29 @@ class _PerformancePageState extends State<PerformancePage> {
padding: EdgeInsets.only(top: 150), padding: EdgeInsets.only(top: 150),
child: Column( child: Column(
children: [ children: [
FutureBuilder<void>( FutureBuilder(
future: computeFuture, future: computeFuture,
builder: (context, snapshot) { builder: (context, snapshot) {
return RaisedButton( return RaisedButton(
child: const Text('Compute on Main'), child: const Text('Compute on Main'),
elevation: 8.0, elevation: 8.0,
onPressed: createMainIsolateCallBack(context, snapshot), onPressed:
snapshot.connectionState == ConnectionState.done
? () => handleComputeOnMain(context)
: null,
); );
}, },
), ),
FutureBuilder<void>( FutureBuilder(
future: computeFuture, future: computeFuture,
builder: (context, snapshot) { builder: (context, snapshot) {
return RaisedButton( return RaisedButton(
child: const Text('Compute on Secondary'), child: const Text('Compute on Secondary'),
elevation: 8.0, elevation: 8.0,
onPressed: onPressed:
createSecondaryIsolateCallBack(context, snapshot), snapshot.connectionState == ConnectionState.done
); ? () => handleComputeOnSecondary(context)
: null);
}, },
), ),
], ],
@ -78,54 +82,40 @@ class _PerformancePageState extends State<PerformancePage> {
); );
} }
VoidCallback createMainIsolateCallBack( void handleComputeOnMain(BuildContext context) {
BuildContext context, var future = computeOnMainIsolate()
AsyncSnapshot snapshot,
) {
if (snapshot.connectionState == ConnectionState.done) {
return () {
setState(() {
computeFuture = computeOnMainIsolate()
..then((_) { ..then((_) {
final snackBar = SnackBar( var snackBar = SnackBar(
content: Text('Main Isolate Done!'), content: Text('Main Isolate Done!'),
); );
Scaffold.of(context).showSnackBar(snackBar); Scaffold.of(context).showSnackBar(snackBar);
}); });
setState(() {
computeFuture = future;
}); });
};
} else {
return null;
}
} }
VoidCallback createSecondaryIsolateCallBack( void handleComputeOnSecondary(BuildContext context) {
BuildContext context, AsyncSnapshot snapshot) { var future = computeOnSecondaryIsolate()
if (snapshot.connectionState == ConnectionState.done) {
return () {
setState(() {
computeFuture = computeOnSecondaryIsolate()
..then((_) { ..then((_) {
final snackBar = SnackBar( var snackBar = SnackBar(
content: Text('Secondary Isolate Done!'), content: Text('Secondary Isolate Done!'),
); );
Scaffold.of(context).showSnackBar(snackBar); Scaffold.of(context).showSnackBar(snackBar);
}); });
setState(() {
computeFuture = future;
}); });
};
} else {
return null;
}
} }
Future<void> computeOnMainIsolate() async { Future<void> computeOnMainIsolate() async {
// A delay is added here to give Flutter the chance to redraw the UI at least // A delay is added here to give Flutter the chance to redraw the UI at
// once before the computation (which, since it's run on the main isolate, // least once before the computation (which, since it's run on the main
// will lock up the app) begins executing. // isolate, will lock up the app) begins executing.
await Future.delayed( await Future<void>.delayed(Duration(milliseconds: 100));
Duration(milliseconds: 100), fib(45);
() => fib(45),
);
} }
Future<void> computeOnSecondaryIsolate() async { Future<void> computeOnSecondaryIsolate() async {
@ -141,24 +131,22 @@ class SmoothAnimationWidget extends StatefulWidget {
class SmoothAnimationWidgetState extends State<SmoothAnimationWidget> class SmoothAnimationWidgetState extends State<SmoothAnimationWidget>
with TickerProviderStateMixin { with TickerProviderStateMixin {
AnimationController _controller; AnimationController _animationController;
Animation<BorderRadius> _borderAnimation; Animation<BorderRadius> _borderAnimation;
@override @override
void initState() { void initState() {
super.initState(); super.initState();
_controller = AnimationController( _animationController =
duration: const Duration(seconds: 1), AnimationController(duration: const Duration(seconds: 1), vsync: this);
vsync: this,
);
_borderAnimation = BorderRadiusTween( _borderAnimation = BorderRadiusTween(
begin: BorderRadius.circular(100.0), begin: BorderRadius.circular(100.0),
end: BorderRadius.circular(0.0), end: BorderRadius.circular(0.0))
).animate(_controller); .animate(_animationController);
_controller.repeat(reverse: true); _animationController.repeat(reverse: true);
} }
@override @override
@ -192,7 +180,7 @@ class SmoothAnimationWidgetState extends State<SmoothAnimationWidget>
@override @override
void dispose() { void dispose() {
_controller.dispose(); _animationController.dispose();
super.dispose(); super.dispose();
} }
} }

@ -73,7 +73,7 @@ packages:
name: provider name: provider
url: "https://pub.dartlang.org" url: "https://pub.dartlang.org"
source: hosted source: hosted
version: "3.1.0" version: "3.1.0+1"
quiver: quiver:
dependency: transitive dependency: transitive
description: description:

Loading…
Cancel
Save