Home > Software design >  Flutter terminate loop when new one starts
Flutter terminate loop when new one starts

Time:01-03

I have a list called songs. I want to perform some action on songs and save them in another list OtherSongs. Here is an example:

Class SongClass{
    List songs = [
      {//song 1},
      {//Song 2},
      ...
    ];
    List otherSongs = [];

    doSomething(){
        otherSongs.clear();
        for(var item in songs){
           // fetch detail of song from internet
           OtherSongs.add(item);
        }
    }
}

what I want to do is when I call doSomething() it starts loop which fetches data from internet. It clearly would take time to complete. but if doSomething() is called again before completing, I want previous loop to stop and then start new one.

CodePudding user response:

One way to achieve this is to use a flag variable to keep track of whether the loop is currently running. You can set the flag to true when the loop starts and set it to false when the loop finishes. Then, you can check the value of the flag before starting the loop. If the flag is true, you can skip the loop and return. Here is an example of how you can modify your doSomething method:

bool _isLoopRunning = false;

doSomething() {
if (_isLoopRunning) return;
_isLoopRunning = true;
otherSongs.clear();
for (var item in songs) {
// fetch detail of song from internet
otherSongs.add(item);
}
_isLoopRunning = false;
}

This way, if the doSomething method is called again before the current loop finishes, it will return and the previous loop will continue until it finishes.

//////////////////

To stop the first loop and not the second loop, you can use a break statement inside the inner loop. Here is an example of how you can modify your doSomething method:

doSomething() {
otherSongs.clear();
for (var item in songs) {
if (_isLoopRunning) break;
// fetch detail of song from internet
otherSongs.add(item);
}
}

CodePudding user response:

To achieve this, you can use a CancelableOperation object to cancel the previous loop when doSomething() is called again before it has completed.

Here is an example of how you can modify your doSomething() method to use a CancelableOperation:

import 'package:async/async.dart';

class SongClass {
  List songs = [
    {}, //song 1
    {}, //Song 2
    //...
  ];
  List otherSongs = [];
  late CancelableOperation _cancelableOperation;

  doSomething() {
    // Cancel the previous operation if it is still running
    _cancelableOperation?.cancel();

    otherSongs.clear();

    // Start a new cancelable operation
    _cancelableOperation = CancelableOperation.fromFuture(
      Future.forEach(songs, (item) async {
        // Fetch detail of song from internet
        otherSongs.add(item);
      }),
    );
  }
}

With this implementation, if doSomething() is called again before the previous loop has completed, the previous loop will be cancelled and a new loop will be started.

  • Related