@@ -6,33 +6,32 @@ import 'package:async/async.dart';
6
6
import 'game_engine.dart' ;
7
7
8
8
class ConcurrentGameEngine implements GameEngine {
9
- final ReceivePort _receivePort = ReceivePort ();
10
- late final StreamQueue <Object ?> _receiveQueue = StreamQueue <Object ?>(
11
- _receivePort,
12
- );
13
- SendPort ? _sendPort;
14
9
Isolate ? _isolate;
10
+ SendPort ? _sendPort;
11
+
12
+ final ReceivePort _receivePort = ReceivePort ();
13
+ late final StreamQueue _receiveQueue = StreamQueue (_receivePort);
15
14
16
15
@override
17
16
Future <UiState > start () async {
18
17
if (_isolate == null ) {
19
18
_isolate = await Isolate .spawn (_isolateEntryPoint, _receivePort.sendPort);
20
- _sendPort = await _receiveQueue.next as SendPort ;
19
+ _sendPort = await _receiveQueue.next;
21
20
}
22
21
_sendPort! .send ('start' );
23
- return ( await _receiveQueue.next) as UiState ;
22
+ return await _receiveQueue.next;
24
23
}
25
24
26
25
@override
27
26
Future <UiState > reportMove (int row, int col) async {
28
27
_sendPort! .send ([row, col]);
29
- return ( await _receiveQueue.next) as UiState ;
28
+ return await _receiveQueue.next;
30
29
}
31
30
32
31
@override
33
32
Future <UiState > makeMove () async {
34
33
_sendPort! .send ('makeMove' );
35
- return ( await _receiveQueue.next) as UiState ;
34
+ return await _receiveQueue.next;
36
35
}
37
36
38
37
@override
@@ -45,22 +44,18 @@ class ConcurrentGameEngine implements GameEngine {
45
44
}
46
45
47
46
void _isolateEntryPoint (SendPort sendPort) {
48
- final ReceivePort receivePort = ReceivePort ();
47
+ final receivePort = ReceivePort ();
49
48
sendPort.send (receivePort.sendPort);
50
49
51
- final GameEngine engine = GameEngine ();
50
+ final engine = GameEngine ();
52
51
53
52
receivePort.listen ((Object ? message) async {
54
- final UiState uiState;
55
53
if (message == 'start' ) {
56
- uiState = await engine.start ();
54
+ sendPort. send ( await engine.start () );
57
55
} else if (message == 'makeMove' ) {
58
- uiState = await engine.makeMove ();
56
+ sendPort. send ( await engine.makeMove () );
59
57
} else if (message is List <int > && message.length == 2 ) {
60
- uiState = await engine.reportMove (message.first, message.last);
61
- } else {
62
- throw Exception ('Invalid message sent to isolate: $message ' );
58
+ sendPort.send (await engine.reportMove (message.first, message.last));
63
59
}
64
- sendPort.send (uiState);
65
60
});
66
61
}
0 commit comments