Home > Blockchain >  How to cancel cubit old function call?
How to cancel cubit old function call?

Time:04-06

I am trying to use cubit in my flutter project but i am facing this problem i am trying to call a function its function with future return type so its need time to be done but at the same time i got a notify so i need to call another function in side this cubit but i want to cancel the previous function first how can i do this thanks for your help .

class ConnectionCheckerCubit extends Cubit<ConnectionCheckerState> {
  ConnectionCheckerCubit() : super(ConnectionCheckerInitial());

  void whenConnectedFunction() {
    print('test1');
  }

  void whenDisconnectedFunction() async {
    print('test2');
    await Future.delayed(Duration(seconds: 10));
    print('test3');
  }
}

i call the second function whenDisconnectedFunction its print test2 then i call the upper function whenConnectedFunction before the 10 seconds end its print test1 but its also test3 is printed how can i fix this problem . thx .

CodePudding user response:

You can't cancel a function once it's called, but what you can do is put a checker once a future is complete to check if the function needs to proceed forward or not.

I have written an example code to help you understand this better, you can paste this is dartpad to try for yourself.

void main() async {
  
  print("Testing without cancel");
  final cubitWithoutCancel = ConnectionCheckerCubit();
  cubitWithoutCancel.whenDisconnectedFunction();
  cubitWithoutCancel.whenConnectedFunctionWithoutCancel();
  
  await Future.delayed(const Duration(seconds: 11));
  
  print("Testing with cancel");
  final cubit = ConnectionCheckerCubit();
  cubit.whenDisconnectedFunction();
  cubit.whenConnectedFunction();
}


class ConnectionCheckerCubit {
  ConnectionCheckerCubit();
  
  bool _cancelFunctionIfRunning = false;

  void whenConnectedFunction() {
    _cancelFunctionIfRunning = true;
    print('test1');
  }
  
  void whenConnectedFunctionWithoutCancel(){
    print('test1');
  }

  void whenDisconnectedFunction() async {
    print('test2');
    await Future.delayed(Duration(seconds: 10));
    if(_cancelFunctionIfRunning) return;
    print('test3');
  }
}

The output of the above code is as follows:

Testing without cancel
test2
test1
test3
Testing with cancel
test2
test1

This is a rather simple implementation to help you understand the concept of how to quit a function midway based on an external factor, you can create a function to do this task for you instead of manually changing a boolean.

  • Related