'Kill an isolate started with compute in flutter

I am trying to run heavy computations in a separate process (by using compute) in order not to block the UI. My problem is that the computations depends on the items on screen, so they would need to change together with the view. What I thought I could do was to start the computation using compute. The problem with that is that if the view changes, the computations started on the previous time will be useless, so I would like to stop them as soon as possible.

This is the function placeholder:

double computeValue(int? value) {
double sum = 0.0;
  int index = 0;
  int count = 20000000;
  
  while(index < count){
    sum += Random().nextDouble();
    index++;
  }
  print("Finished Computation!");
  return sum / count;
}

If I run this function when touching, everything works correctly, the UI doesn't freeze and after around 5s I get the result back. My problem is that if I touch the button again before the first function has finished running, it would run to completion 2 times. I tried using Isolate.spawn in place of compute and killing the isolate with Isolate.kill before spawning it again but it still runs to completion both times. Is there a way I could successfully stop a method I called with Isolate.spawn or compute?



Solution 1:[1]

I think you you would like to disable the button until you get the result from compute function and enable it again

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bencherif