I have an app uploading joystick position data to a webserver using an API call.
This method gets called when a joystick is moved. It stops any previously running isolate and starts a new isolate if the joystick is not in the centre.
void onJoystickMoved(double angle, double distance) {
stopIsolate();
if(distance > 0.06){
startIsolate(JoystickPosition.fromDistanceAndRadius(distance, angle));
}
}
The isolate start and stop methods
Future<void> startIsolate(JoystickPosition position) async {
isolate = await Isolate.spawn(uploadJoystickPosition, position);
}
void stopIsolate() {
if (isolate != null) {
debugPrint("Stopping isolate");
isolate.kill();
isolate = null;
}
}
uploadJoystickPosition method (the method in the isolate):
void uploadJoystickPosition(JoystickPosition position){
Timer.periodic(new Duration(seconds: 1), (Timer t) {
DataModel dataModel = DataModel(1, getTimeInSeconds());
dataModel.joystickPosition = position;
debugPrint("Distance: ${position.distance}");
uploadData(dataModel).then(uploadResponse, onError: uploadError);
});
}
Trouble is the uploadJoystickPosition keeps uploading old positions of the joystick along with new positions. I am assuming this is because the timer keeps running even when the isolate is killed.
Questions:
- Why does my timer keep going(and uploading) even after I kill the isolate?
- How do I get my timer to stop when I kill the isolate its running in?